Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to external DLL from C# with integer pointer

Tags:

c++

c#

interop

dll

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!

like image 936
Hank Brandenburg Avatar asked Mar 20 '23 18:03

Hank Brandenburg


1 Answers

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?

like image 108
Ben Voigt Avatar answered Apr 06 '23 20:04

Ben Voigt