2017-06-20 64 views
0

指針調用C功能我有以下問題:與從C#的.NET代碼

我必須使用C語言編寫的外部DLL庫,它實現了一個函數有兩個指針作爲函數的輸入。我不知道如何從C#這樣做......是這樣的:

typedef struct{ 
double[3] dArray; 
int a; 
int b; 
}myInput 

[...]

myFunction(myInput *input) 

我可以定義在C#中類似的結構,但我不能讓我的代碼正常工作 從C#中可以做到這一點嗎?先謝謝你!

+0

int(16,32,64)的大小是多少? – jdweng

回答

0

嘗試這樣的代碼。我不確定int和double的大小。 Int中的c可以是16,32或64. Double可以是4或8(通常是8)。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Runtime.InteropServices; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     [DllImport("XXXXXXXX.dll", CallingConvention = CallingConvention.Cdecl)] 
     public static extern void myFunction(IntPtr input); 

     [StructLayout(LayoutKind.Sequential, Pack = 1)] 
     public struct MyInput 
     { 
      [MarshalAs (UnmanagedType.ByValArray, SizeConst = 3)] 
      double[] dArray; 
      int a; 
      int b; 
     } 

     static void Main(string[] args) 
     { 
      MyInput myInput = new MyInput(); 
      IntPtr dataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(myInput)); 
      Marshal.StructureToPtr(myInput, dataPtr, true); 

      myFunction(dataPtr); 

     } 
    } 


}