在 C# 中调用此 C 函数的正确语法是什么?该函数使用指针和数组

本文关键字:函数 是什么 数组 指针 语法 调用 | 更新日期: 2023-09-27 18:37:21

我正在尝试从用 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,这在文档中被指定为错误。这是我遇到过的最好的结果,因为我在尝试不同的refout组合时遇到了许多堆栈溢出错误

在 C# 中调用此 C 函数的正确语法是什么?该函数使用指针和数组

你快到了。最后一个论点是我认为的问题。尝试如下:

[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);

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 函数,然后它负责其余的。