0

Having in C++:

extern "C" MY_API int connect(const char* pcHost,const int nPort, ConnectionId_T *pConId);

Being:

  • pcHost an IP
  • nPort a port
  • pConId a constant (-1)

My try is:

[DllImport("my.dll", CharSet = CharSet.Ansi)]
public static extern int connect(StringBuilder pcHost, int nPort, ConnectionId_T pConId);

But when I try to connect:

StringBuilder ip = new System.Text.StringBuilder();
ip.Append("1.1.1.1");
int nPort = 1111;
ConnectionId_T nConId = MY_NCONID // This is defined previously as -1 (public const int MY_NCONID = -1)
connect(ip, nPort, nConId))

I get an AccesViolationException on the connect line. Do I've my marshal wrong?

PS: ConectionId_T is defined as using ConnectionId_T = System.Int32;

Thanks in advance.

Avión
  • 7,963
  • 11
  • 64
  • 105

2 Answers2

-1
PS: ConectionId_T is defined as using ConnectionId_T = System.Int32;

Based on this, if I assume ConnectionId_T is nothing but int in C++ world, then you need to change the function import as:

[DllImport("my.dll", CharSet = CharSet.Ansi)]
public static extern int connect(StringBuilder pcHost, int nPort, IntPtr pConId);

Or as:

[DllImport("my.dll", CharSet = CharSet.Ansi)]
public static extern int connect(StringBuilder pcHost, int nPort, ref int pConId);
Ajay
  • 18,086
  • 12
  • 59
  • 105
-2
[DllImport("my.dll", CharSet = CharSet.Ansi,CallingConvention=CallingConvention.Cdecl)]
public static extern int connect(IntPtr pcHost, int nPort, ref ConnectionId_T pConId);

and use Intptr pcHost = Marshal.StringToHGlobalAnsi(pcHostString))

Mujahid Daud Khan
  • 1,983
  • 1
  • 14
  • 23