这是 native c 方法的签名:
bool nativeMethod1
(unsigned char *arrayIn,
unsigned int arrayInSize,
unsigned char *arrayOut,
unsigned int *arrayOutSize);
我不知道为什么 arrayOutSize 是指向 unsigned int 而不是 int 本身的指针。
这是我从 C# 调用它的方式:
byte[] arrayIn= Encoding.UTF8.GetBytes(source);
uint arrayInSize = (uint)arrayIn.Length;
byte[] arrayOut = new byte[100];
uint[] arrayOutSize = new uint[1];
arrayOutSize[0] = (uint)arrayOut.Length;
fixed (byte* ptrIn = arrayIn, ptrOut = arrayOut)
{
if (nativeMethod1(ptrIn, arrayInSize, ptrOut, arrayOutSize))
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
}
和一些DllImport
代码
[DllImport(@"IcaCert.dll", EntryPoint = "CreateCert2", CallingConvention = CallingConvention.Cdecl)]<br>
public unsafe static extern bool CreateCert2WithArrays(
byte* data, uint dataSize,<br>
byte* result, uint[] resultSize);
根据文档, native 方法应返回 arrayOut,其值取决于 arrayIn。如果其大小小于所需大小,则返回 false。否则是真的。我认为它需要 arrayOut 中的 850 个元素。所以,当我创建新的 byte[100] 数组时,函数应该返回 false,但它总是返回 true。为什么?
最佳答案
您不需要不安全的代码并已在此处修复。标准的 P/Invoke 编码器不仅仅是完成任务:
[DllImport(@"IcaCert.dll", EntryPoint = "CreateCert2", CallingConvention = CallingConvention.Cdecl)]
public static extern bool CreateCert2WithArrays(
byte[] arrayIn,
uint arrayInSize,
byte[] arrayOut,
ref uint arrayOutSize
);
byte[] arrayIn = Encoding.UTF8.GetBytes(source);
uint arrayInSize = (uint)arrayIn.Length;
uint arrayOutSize = 0;
CreateCert2WithArrays(arrayIn, arrayInSize, null, ref arrayOutSize);
byte[] arrayOut = new byte[arrayOutSize];
CreateCert2WithArrays(arrayIn, arrayInSize, arrayOut, ref arrayOutSize);
我不确定函数的协议(protocol)是什么,但如果输出数组的大小为 0,此类函数能够接收 NULL
是正常的。
关于c# - PInvoke问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6403243/