C# 调用C接口

(1) C 返回 char* 中C# 处理方法

------CSHARP ::

[DllImport(DLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr luna_genGvoiceToken(ref int time, int type, string openId, string room, string client_ip, string member_id, string file);

public static string genGvoiceToken(ref int time, int type, string openId, string room, string client_ip, string member_id, string file)
{
  return Marshal.PtrToStringAnsi(luna_genGvoiceToken(ref time, type, openId, room, client_ip, member_id, file));
}

C#调用C的时候 不要随便传null

---------C++ ::

LUNA_API const char* luna_genGvoiceToken(int* time , int type, const char* open_id, const char* room_name, const char* client_ip, const char* member_id, const char* file_key){
  int ret = gvoice::genGvoiceToken(*_tokenRet, (gvoice::GEN_TYPE)type, open_id, room_name, client_ip, member_id, file_key);
  if (ret) {
  return "";
  }
  *time = _tokenRet->timestamp;
  return _tokenRet->token.c_str();
}

C#中的引用可以对应的C函数中的指针

从C 返回值给C#的时候 不要用memcpy();给C# 传入的ref赋值, 要出错, 指针无法共用。

========

犯的错:

1,memcpy 给C#传入的char *  赋值

2,C#传NULL给C++ 的char *, 转string;

3, .so 库文全局变量 是否有问题??

原文地址:https://www.cnblogs.com/blackcatx/p/6248834.html