我有以下C函数:
LIBRARY_API HRESULT LA_CC GetRSAKeyPair(STRTYPE privateKeyPtr, STRTYPE publicKeyPtr)
{
int length = 2048;
string privateKey, publicKey;
if (GenerateRSAKeyPair(privateKey, publicKey) == false)
{
return FAIL;
}
#ifndef _WIN32
*privateKeyPtr = '\0'; // assumes `dest_size > 0`
strncat(privateKeyPtr, privateKey.c_str(), length);
*publicKeyPtr = '\0'; // assumes `dest_size > 0`
strncat(publicKeyPtr, publicKey.c_str(), length);
#else
*privateKeyPtr = L'\0'; // assumes `dest_size > 0`
wcsncat(privateKeyPtr, toUTF16(privateKey).c_str(), length);
*publicKeyPtr = L'\0'; // assumes `dest_size > 0`
wcsncat(publicKeyPtr, toUTF16(publicKey).c_str(), length);
#endif
return OK;
}
使用pinvoke调用:
[DllImport(DLL_FILE_NAME, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern int GetRSAKeyPair(StringBuilder privateKey, StringBuilder publicKey);
使用时:
StringBuilder privateKey = new StringBuilder(2048);
StringBuilder publicKey = new StringBuilder(2048);
LibraryNative.GetRSAKeyPair(privateKey, publicKey);
Console.WriteLine(privateKey);
Console.WriteLine(publicKey);
输出以中文返回数据,尽管相同的代码在Windows上运行良好。本机库假设编码在非windows平台上不是utf-16,但stringbuilder似乎也期望在nix上使用utf-16。