2016-03-04 78 views
1

我想從用C編寫的DLL調用函數。我需要調用C#中的函數,但我相信我遇到了語法問題。我有一個使用Python中的ctypes庫的工作示例。不幸的是,DLL需要運行一個軟件狗,所以現在我正在尋找有關C,Python和C#語法之間任何明顯差異的幫助。在C#中調用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

+1

數組已被編組爲一個指向第一個元素的指針。所以我認爲'ByRef theArray()As Double'應該是'theArray()As Double'。 –

+0

謝謝你的建議。我將編輯原始問題的底部,因爲我不確定如何清晰地格式化評論。 – jalconvolvon

+0

我把問題轉移到了C#上,因爲這似乎是我在尋求幫助時遇到的最常見的語言。我還從文檔中添加了有關輸入/輸出和功能目的的更多信息。 – jalconvolvon

回答

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); 
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函數的第一個元素,然後把它照顧了剩下的。

+0

這是不對的。你需要將數組聲明爲一個數組。 –

+0

我也不相信語法,但它正確地填充我的dat數組。我不確定文檔是否有錯誤,但這個確切的代碼適用於我打電話的功能。我接受了你的答案,因爲你的語法是有道理的,應該已經工作了,但是代碼本身返回了一個錯誤。 – jalconvolvon