I need to import a C-function which is descripted as
我需要导入一个描述为的C函数
int Read(LPBYTE data, LPBYTE lengthOfData);
The documentation says the following:
文档说明如下:
data
[out] data which was read
[out]读取的数据
lengthOfData
[out] length of data which was read
[out]读取的数据长度
And there is the following example of using this function:
以下是使用此功能的示例:
int num = 0;
BYTE data[16] = {0};
while (num < 6)
{
int dataLen = 0;
Read(data, &dataLen);
num += dataLen;
}
How to import this function?
As I understand, the first one parameter is an array of bytes.
如何导入此功能?据我所知,第一个参数是一个字节数组。
Can I import it as:
我可以将其导入为:
public static extern int Read([Out] IntPtr data, [Out] byte dataLength);
or I should use out
keyword, maybe?
或者我应该使用关键字,也许?
1 个解决方案
#1
If the function really is:
如果功能真的是:
int Read(LPBYTE data, LPBYTE lengthOfData);
Then the correct translation would be:
那么正确的翻译将是:
[DllImport(..., CallingConvention = CallingConvention.Cdecl)]
static extern int Read([Out] byte[] data, out byte dataLength);
But that doesn't match your C code. The C code won't even compile mind you. Perhaps the second parameter is really an int
.
但这与您的C代码不符。 C代码甚至不会编译你。也许第二个参数实际上是一个int。
To call this function you need to allocate the array before calling.
要调用此函数,您需要在调用之前分配数组。
byte[] data = new byte[16];
byte dataLength;
int retval = Read(data, out dataLength);
You need to clear up the following details:
您需要清除以下详细信息:
- What is the type of that second parameter?
- What is the calling convention?
- How do you determine how to pre-allocate the array?
第二个参数的类型是什么?
什么是召集惯例?
你如何确定如何预先分配数组?
The function is poorly designed because it does not allow the caller to specify how long the array is and thus runs the risk of buffer overrun.
该函数设计不当,因为它不允许调用者指定数组的长度,因此存在缓冲区溢出的风险。
#1
If the function really is:
如果功能真的是:
int Read(LPBYTE data, LPBYTE lengthOfData);
Then the correct translation would be:
那么正确的翻译将是:
[DllImport(..., CallingConvention = CallingConvention.Cdecl)]
static extern int Read([Out] byte[] data, out byte dataLength);
But that doesn't match your C code. The C code won't even compile mind you. Perhaps the second parameter is really an int
.
但这与您的C代码不符。 C代码甚至不会编译你。也许第二个参数实际上是一个int。
To call this function you need to allocate the array before calling.
要调用此函数,您需要在调用之前分配数组。
byte[] data = new byte[16];
byte dataLength;
int retval = Read(data, out dataLength);
You need to clear up the following details:
您需要清除以下详细信息:
- What is the type of that second parameter?
- What is the calling convention?
- How do you determine how to pre-allocate the array?
第二个参数的类型是什么?
什么是召集惯例?
你如何确定如何预先分配数组?
The function is poorly designed because it does not allow the caller to specify how long the array is and thus runs the risk of buffer overrun.
该函数设计不当,因为它不允许调用者指定数组的长度,因此存在缓冲区溢出的风险。