我正在尝试从用 C 编写的 DLL 中调用一个函数。我需要在 C# 中调用该函数,但我相信我遇到了语法问题。我有一个使用 ctypes 的工作示例Python 中的库。不幸的是,DLL 需要加密狗才能运行,所以现在我正在寻求帮助,以解决 C、Python 和 C# 之间语法上的任何明显差异。
C函数的格式
int (int nID, int nOrientation, double *pMTFVector, int *pnVectorSize );
(我真的不熟悉指针,PDF 文档中的星号被空格包围,所以我不确定星号应该附加到什么地方)
此代码的功能是接受 nID 和 nOrientation 来指定图像中的特征,然后用值填充数组。该文档描述了以下输出:
out; pMTFVector; array of MTF values, memory is allocated and handled by application, size is given by pnVectorSize
in,out; pnVectorSize maximum number of results allowed to store in pMTFVector, number of results found and stored in pMTFVector
实际工作的 python 代码是:
lib=cdll.LoadLibrary("MTFCameraTester.dll")
lib.MTFCTGetMTF(c_uint(0), c_int(0), byref((c_double * 1024)()), byref(c_uint(1024)))
我试过的代码是:
[DllImport("MTFCameraTester.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public extern static MTFCT_RETURN MTFCTGetMTF(UInt32 nID, int orientation, double[] theArray, IntPtr vectorSize);
double[] myArray = new double[1024];
IntPtr myPtr = Marshal.AllocHGlobal(1024);
returnEnum = MTFCTGetMTF(0, 0, myArray, myPtr);
当代码运行时,我的 returnEnum
是 -1
,这在文档中被指定为错误。这是我遇到的最好的结果,因为在尝试 ref
和 out
最佳答案
你快到了。最后一个参数是我认为的问题。像这样尝试:
[DllImport("MTFCameraTester.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static MTFCT_RETURN MTFCTGetMTF(
uint nID,
int orientation,
[Out] double[] theArray,
ref int vectorSize
);
....
double[] myArray = new double[1024];
int vectorSize = myArray.Length;
MTFCT_RETURN returnEnum = MTFCTGetMTF(0, 0, myArray, ref vectorSize);
关于c# - 在 C# 中调用此 C 函数的正确语法是什么?该函数使用指针和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785726/