调用 C 代码时避免 AccessViolationException
avoid AccessViolationException when calling c code
我正在使用 c# 通过 DLL 调用 c 代码,在调用方法时出现 AccessViolationException,这是源头文件中的代码
extern __declspec( dllexport )
int ReadCardSN( IN OUT unsigned char* CardSN );
在我的 C# 代码中我使用
public static byte[] Data = new byte[4];
[DllImport("CardLib.dll")]
public static extern Int32 ReadCardSN(byte[] Data);
int resCode = ReadCardSN(Data);
可能是什么问题?
错误是因为你的缓冲区太小了。示例代码显示使用长度为 10240 的缓冲区。您提供长度为 4 的缓冲区。
正如所写,C 代码似乎使用默认的 cdecl 调用约定。您的 C# 代码使用 stdcall。
最好将 [In, Out]
属性应用于参数。因为 byte[]
是 blittable 这不是绝对必要的,但它在语义上是准确的。
我正在使用 c# 通过 DLL 调用 c 代码,在调用方法时出现 AccessViolationException,这是源头文件中的代码
extern __declspec( dllexport )
int ReadCardSN( IN OUT unsigned char* CardSN );
在我的 C# 代码中我使用
public static byte[] Data = new byte[4];
[DllImport("CardLib.dll")]
public static extern Int32 ReadCardSN(byte[] Data);
int resCode = ReadCardSN(Data);
可能是什么问题?
错误是因为你的缓冲区太小了。示例代码显示使用长度为 10240 的缓冲区。您提供长度为 4 的缓冲区。
正如所写,C 代码似乎使用默认的 cdecl 调用约定。您的 C# 代码使用 stdcall。
最好将 [In, Out]
属性应用于参数。因为 byte[]
是 blittable 这不是绝对必要的,但它在语义上是准确的。