Search code examples
c#c++dllentry-point

How to properly create an entry point on an external .dll resource written in C++ consumed in C#


Long time reader, first time poster. One day I hope to be answering questions on here...

So it's kind of similar to: "Unable to find an entry point named [function] in dll" (c++ to c# type conversion)

But I can't seem to apply the same solution...

Basically, I wrote a new Method:

Defined in the header file of the C++ project as :

extern "C" {
     __declspec(dllexport) bool IsDataValid();
}

Defined in the source file of the C++ project as: (signiature only)

extern bool __cdecl IsDataValid() { 
//function stuf......... returns a bool
}

Imported into a forms C# application within the C# Project as:

[DllImport("CarChipSDK_C_Sharp.dll", EntryPoint = "IsDataValid")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsDataValid();

It is called from the same place within C# forms .cs file as:

bool isDataValid = IsDataValid();

It is returning an exception with the message:

"Unable to find an entry point 'IsDataValid()' named in DLL 'CarChipSDK_C_Sharp.dll'.

I have used dumpbin.exe and dependency walker on the .dll generated from the c++ code and it shows that it has the IsDataValid() entry point.

All help is much appreciated...

Problem Solved! Stupid me, this was the code from a previous co-op at my current company, turns out he was reading the .dll from the bin/release folder where as I was building to the bin/debug folder. Should have known. My sincere apologies.


Solution

  • You are encountering C++ name mangling. Declare the C++ functions as extern "C". So, in your C++ module...

    extern "C" __declspec(dllexport) bool IsDataValid();
    

    You really don't need the entry point specification attribute either. Your C# declaration will be:

    [DllImport("CarChipSDK_C_Sharp.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool IsDataValid();
    

    For future reference, dumpbin.exe is a very useful program for analyzing problems like this. If you run it on your DLL you will see what those functions are actually named by the time they are compiled.