【发布时间】:2011-06-19 23:34:08
【问题描述】:
这是原生 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);
根据文档,本机方法应返回 arrayOut,其值取决于 arrayIn。如果它的大小小于需要,则返回 false。否则为真。我认为它需要 arrayOut 中的 850 个元素。所以,当我创建新的 byte[100] 数组时,函数应该返回 false,但它总是返回 true。为什么?
【问题讨论】:
-
你为什么使用不安全的代码并修复。这里不需要。
-
但是我用的是byte*指针,需要不安全,而且这部分byte* ptrIn = arrayIn需要固定。
-
你不需要使用
byte*- 看我的回答 -
您不能使用 fixed 关键字来生成传递给本机代码的指针,数组未固定。大卫的声明是正确的。使用 Project + Properties 调试本机代码,调试,启用非托管代码调试。