C#调C开发的DLL动态库返回数据不完整。
C 方法
extern "C" _declspec(dllexport) int jiami(int business, char* plaintext, int64_t pstSessionKey, char* pcCipherBuffout, unsigned int* ciplenOut);
C# 方法
[DllImport("DemoQssServiceSDK.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int jiami(int business, string plaintext, long pstSessionKey, byte[] outData, ref uint ciplenOut);
目的是在C#中获取此参数 pcCipherBuffout 数据,然后把数据转成hexstring;
试了用StringBuilder、Intptr、string去接收都不行,要么得到乱码要么直接异常,最后选择用Byte[]接收。
紧接着又出现问题,C里实际数据字节数与C#得到的字节数不一致,排查是字节数组中有 \0 ,
C中默认以 \0 代表字符结尾 猜测与这个有关。
解决方案,直接在 C 中将数据转为hexstring再返回给 C# ,目前使用正常。
网上找的 C char*转hexstring方法
void charToHex(char c, char* hex) {
static const char hexDigits[] = "0123456789ABCDEF";
hex[0] = hexDigits[(c >> 4) & 0xF]; // 高4位
hex[1] = hexDigits[c & 0xF]; // 低4位
hex[2] = '\0'; // 字符串结束符
}
// 将char*转换为十六进制字符串
char* stringToHex(const char* str, unsigned int __Ciplen) {
if (str == NULL) return NULL;
int len = __Ciplen;// strlen(str); // 获取字符串长度
char* hexStr = (char*)malloc(len * 2 + 1); // 为每个字符分配2个字节(十六进制表示)+1为结束符
if (hexStr == NULL) return NULL; // 内存分配失败处理
for (int i = 0; i < len; i++) {
charToHex(str[i], hexStr + i * 2); // 转换并存储到结果字符串中
}
hexStr[len * 2] = '\0'; // 确保字符串正确结束
return hexStr;
}