使用" const char *"在C#中编组我的C ++ .dll和" const int"

时间:2016-05-26 10:35:20

标签: c# c++ marshalling

使用C ++:

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

存在:

  • pcHost知识产权
  • nPort一个端口
  • pConId一个常数(-1)

我的尝试是:

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

但是当我尝试连接时:

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))

我在connect行上收到 AccesViolationException 。我的元帅错了吗?

PS:ConectionId_T定义为using ConnectionId_T = System.Int32;

提前致谢。

2 个答案:

答案 0 :(得分:-1)

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

基于此,如果我假设{C}世界中ConnectionId_T只是int,那么你需要将函数import更改为:

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

或者作为:

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

答案 1 :(得分:-2)

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

并使用Intptr pcHost = Marshal.StringToHGlobalAnsi(pcHostString))