Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have written a VC++ dll. The declaration for one of the methods in the dll is as follows:

extern "C" _declspec(dllexport)
void startIt(int number)
{
     capture = cvCaptureFromCAM(number);
}

I use this dll in a C# code using P/Invoke. I make the declaration as:

[DllImport("Tracking.dll", EntryPoint = "startIt")]
        public extern static void startIt(int number);

and I call the function in the code as:

startIt(0);

Now, when this line is encountered, the compiler is throwing me this error:

A call to PInvoke function 'UsingTracking!UsingTracking.Form1::startIt' has 
unbalanced the stack. This is likely because the managed PInvoke signature does 
not match the unmanaged target signature. Check that the calling convention 
and parameters of the PInvoke signature match the target unmanaged signature.

I cannot understand why is it throwing this error as the signature in both managed and unmanaged code are the same. Moreover, in my another machine, the same code is running perfectly in visual studio. So, this makes me think that the error thrown is mis leading.

Please help.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
249 views
Welcome To Ask or Share your Answers For Others

1 Answer

When you p/invoke an external function, the calling convention used defaults to __stdcall. Since your function uses the __cdecl convention, you need to declare it as such:

[DllImport("Tracking.dll", EntryPoint = "startIt",
    CallingConvention = CallingConvention.Cdecl)]
public extern static void startIt(int number);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...