marsh-wiggle
marsh-wiggle

Reputation: 2813

How to call from C# simple function in C++ DLL

i have a simple function in c++ (not a method of a class)

__declspec(dllexport) extern "C" void __stdcall TestFunc();  

i try to call it from c#:

[DllImport("ImportTest.dll")]  
public static extern void TestFunc();  

...  

TestFunc();

It throws an "entry point could't be found" exception.

Whats wrong?

Thank you for helping me :)

Upvotes: 0

Views: 2937

Answers (2)

Spook
Spook

Reputation: 25929

Try (guessing, that DLL is written in VS)

extern "C" __declspec(dllexport) void __stdcall TestFunc();

That's:

  • __declspec(dllexport) to notify compiler, that this function is to be exported from the DLL;
  • extern "C" mainly to prevent function name decorations;
  • __stdcall, because this is default calling convention if you specify none in [DllImport] directive.

In the future, you can check if your function is exported from DLL using Dll export viewer.

Upvotes: 5

vathsa
vathsa

Reputation: 303

In C++ function , at header(if your function is declared in header) add

extern "C" _declspec(dllexport) void TestFunc();

at the function definition use

_declspec(dllexport) void TestFunc()
{

}

At C# side,you need to declare a function like

[DllImport(@"ImportTest.dll",
                 EntryPoint = "TestFunc",
                 ExactSpelling = false,
                 CallingConvention = CallingConvention.Cdecl)]
            static extern void NewTestFunc()

Now use , NewTestFunc()

Upvotes: 2

Related Questions