Search code examples
c#dlldllimportlabview

Function Parameters for LabVIEW DLL


I am trying to call a function from a DLL generated in LabVIEW. I thought this was going to be far more straightforward than it is turning out to be. The function is described below:

void __cdecl Device_Init(char DevName[]);

So in my C# code I am trying the following:

[DllImport(@"Device.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void Device_Init(StringBuilder name);

I call this in my application by simply using the following:

StringBuilder devName = new StringBuilder(DeviceName);
Device_Init(devName);

Rather than getting any initialization on my device, I see a LabVIEW vi window pop up that has a title akin to a different method within the dll (i.e. AF1_GetPressure.vi). The application then hangs with this LabVIEW window popped up and I have to exit the debugging session.

I guess my question is how my function signature might be erroneous... I used StringBuilder as I found an example on the NI website that seemed to indicate that LabVIEW requires this variable type to better ascertain the number of characters in the array. http://www.ni.com/example/31050/en/

I have tried all kinds of different combinations of parameter types but I simply can't seem to get this to work. If I try calling the dll from C++ then I can get things to work. Although, oddly, I had to dynamically load the dll in C++ because I was getting a dll initialization failure when I tried to load it with the application.

Any help would be greatly appreciated!


Solution

  • I was able to build a DLL with LabView 2012, and import it into a .NET 4.0 console application, call the function, and receive a result. Here is a screenshot of the VI:

    LabView VI

    And here is the import statement in C#:

    [DllImport(@"SharedLib.dll", CallingConvention = CallingConvention.Cdecl)] 
    private static extern int StringLength(string str);
    

    I would recommend trying something very simple like this and see if you can get it working.

    I should note that I tried passing my parameter as a StringBuilder object and that worked as well - and I didn't expect it to!

    Also, I recommend posting this question on the LabView forums. I was always able to get a very quick response there, and I think with LabView, you're likely to get a better response there than StackOverflow.

    As requested, here are the contents of the .h file generated by LabView:

    #include "extcode.h"
    #pragma pack(push)
    #pragma pack(1)
    
    #ifdef __cplusplus
    extern "C" {
    #endif
    
    /*!
     * StringLength
     */
    int32_t __cdecl StringLength(char String[]);
    
    long __cdecl LVDLLStatus(char *errStr, int errStrLen, void *module);
    
    #ifdef __cplusplus
    } // extern "C"
    #endif
    
    #pragma pack(pop)