Search code examples
c#.netvisual-c++pinvoke

invoke C function from C# using P/Invoke


I have a C function, which is part of a VS 2010 project and has this signature:

real_T wrapper(void)

where

typedef double real_T;

In my C# code I attempt this:

[DllImport(@"C:\Users\bla\Documents\Visual Studio 2010\Projects\bla\bla\Debug\bladibla.dll")]
public static extern double wrapper();

static void Main(string[] args)
{
    wrapper();
}

but get:

Unable to find an entry point named 'wrapper' in DLL 'C:\Users\bla\Documents\Visual Studio 2010\Projects\bla\bla\Debug\bladibla.dll'.

The dll is definitely there. What else could be wrong?


Solution

  • Possibly the function is being exported with a mangled name. You can suppress the mangling like this:

    extern "C" {
        real_T wrapper(void);
    }
    

    You aren't obviously exporting the function either. The simple way to do that is like this:

    extern "C" {
        __declspec(dllexport) real_T wrapper(void);
    }
    

    If that still doesn't resolve the missing export, use a tool like Dependency Walker to check whether the function is in fact being exported, and if so under what name.

    Finally, you should declare the calling convention on the C# side to be cdecl to match the calling convention of your native function.

    [DllImport(@"...", CallingConvention=CallingConvention.Cdecl)]
    public static extern double wrapper();