Search code examples
c#c++pinvokedllimportextern

How to set up a C++ function so that it can be used by p/invoke?


Hopefully this is a brainlessly easy question, but it shows my lack of expertise with C++. I'm a C# programmer, and I've done extensive work with P/Invoke in the past with other people's C++/C dlls. However, this time I've decided to write a wrapper C++ dll (unmanaged) myself, and am then calling my wrapper dll from C#.

The problem I am immediately running into is that I am unable to define a C++ function that can be found by p/invoke. I don't know what the syntax for this is, but here's what I'm trying so far:

extern bool __cdecl TestFunc()
{
  return true;
}

Originally I simply had this, but it did not work either:

bool TestFunc()
{
  return true;
}

And then on the C# side, I have:

    public const string InterfaceLibrary = @"Plugins\TestDLL.dll";

    [DllImport( InterfaceLibrary, CallingConvention = CallingConvention.Cdecl,
        EntryPoint = "TestFunc" ), SuppressUnmanagedCodeSecurity]
    internal static extern bool TestFunc();

Everything compiles, but when I execute this C# p/invoke call, I get a System.EntryPointNotFoundException: Unable to find an entry point named 'TestFunc' in DLL 'Plugins\TestDLL.dll'.

Surely this must be something incredibly simple on the C++ end that I just don't know the syntax for.


Solution

  • You'll want to use extern "C" as well as __declspec(export), like so:

    extern "C" _declspec(dllexport)  bool TestFunc()
    {
        return true;
    }
    

    For full details, see MSDN on Marshalling Types.