我正在尝试用C编写的DLL调用函数。我需要在C#中调用该函数,但我相信我遇到了语法问题。我有一个在Python中使用ctypes库的工作示例。不幸的是,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
答案 0 :(得分:1)
你快到了。最后的论点是我认为的问题。试试这样:
[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);
答案 1 :(得分:0)
有效的VB.NET解决方案是:
<DllImport("MTFCameraTester.dll", CallingConvention:=CallingConvention.Cdecl)> _
Function MTFCTGetMTF(ByVal id As UInt32, ByVal orientation As UInt32, ByRef data As Double, ByRef len As UInt32) As Integer
End Function
Dim ret As Integer
Dim dat(1023) As Double
Dim len As UInt32 = 1024
ret = MTFCTGetMTF(0, 0, dat(0), len)
似乎我必须将数组的第一个元素传递给C函数,然后它会处理其余部分。