Call to external DLL from C# with integer pointer

2019-07-21 12:00发布

I'm trying to call an external .dll function from c#. The doc for the dll defines the function:

int funcName(int *retVal)

I've tried various configurations and always the unbalanced stack error from p/invoke; My c# code currently looks like this:

[DLLImport("dllName");
unsafe static extern int funcName(ref IntPtr retVal);
unsafe IntPtr retNum;
int status = funcName(ref retNum);

Any ideas are appreciated!

标签: c# c++ dll interop
1条回答
Anthone
2楼-- · 2019-07-21 12:20

Your p/invoke declaration has the wrong parameter type.

  • ref Int32 is the correct match for int*.

  • IntPtr can also work.

  • ref IntPtr would be int**. Definitely not what you want.

Use

[DLLImport("dllName")]
static extern int funcName(ref Int32 retVal);

Also make sure that the calling convention matches. You should never use a dllexport in C or C++ without also using an explicit calling convention, and then the C# DllImport needs to have the matching convention.

Generally the prototype in C++ should be

extern "C" int __stdcall funcName(int* arg);

Is there a header file provided for C and C++ clients that you could check to verify the signature?

查看更多
登录 后发表回答