C#调C动态库方法获取数据不完整

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嘿呦嘿呦嘿呦嘿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值