2013-06-19 56 views
0

我有一个问题,我无法在网上找到答案。 我想从我的C#代码中调用一个C++函数。 C++函数声明为:如何将包含void *的结构从C++传递到c#?

int read(InfoStruct *pInfo, int size, BOOL flag) 

结构如下

typedef struct 
{ 
    int ID; 
    char Name[20]; 
    double value; 
    void *Pointer; 
    int time; 
}InfoStruct; 

在我的C#代码,我写道:

public unsafe struct InfoStruct 
{ 
    public Int32 ID; 
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)] 
    public string Name; 
    public Double value; 
    public void *Pointer; 
    public Int32 time; 
    }; 

[DllImport("mydll.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)] 
     public static extern unsafe int read(out MeasurementInfoStruct[] pInfo, int size, bool flag); 

我试图运行的代码,但它崩溃所以我想我对这个结构特别是void *犯了一个错误,但是我无法弄清楚需要改变什么。也可能是这个函数返回一个结构数组,也许我没有把它调用正确。 你能帮我解决吗? 非常感谢。

+3

您是否尝试过的IntPtr? –

+0

你必须编组每个C#中的类变量,并尝试在C#中使用引用而不是intptr。如果可能的话,会尽力为您解决问题并发布解决方案。 – 2013-06-19 10:23:24

+0

我尝试IntPtr没有成功。 – diditexas

回答

0

我创建了一个测试应用程序和代码如下,它是工作的罚款...

// CPP code 

typedef struct 
{ 
    int ID; 
    char Name[20]; 
    double value; 
    void *Pointer; 
    int time; 
}InfoStruct; 

int WINAPI ModifyListOfControls(InfoStruct *pInfo, int size, bool flag) 
{ 

    int temp = 10; 
    pInfo->ID = 10; 
    strcpy(pInfo->Name,"Hi"); 
    pInfo->value = 20.23; 
    pInfo->Pointer = (void *)&temp; 
    pInfo->time = 50; 
    return 0; 
} 
/***************************************************/ 
// This is C# code 
[StructLayout(LayoutKind.Sequential)] 
public struct InfoStruct 
{ 
    public Int32 ID; 
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)] 
    public string Name; 
    public Double value; 
    public IntPtr Pointer; 
    public Int32 time; 
}; 


[DllImport(@"D:\Test\Projects\Release_Build\WeldDll.dll", CallingConvention = CallingConvention.Winapi)] 
public static extern int ModifyListOfControls(ref InfoStruct pInfo, int size, bool flag);// ref InfoStruct pi); 

public static void Main() 
{ 
    InfoStruct temp = new InfoStruct(); 

    temp.Pointer = new IntPtr(); 

    ModifyListOfControls(ref temp, 200, true); 

    Console.WriteLine(temp.ID); 
    Console.WriteLine(temp.Name); 
    Console.WriteLine(temp.time); 
    Console.WriteLine(temp.value); 


    Console.ReadLine(); 
} 

/* ** * **输出* ** * ** * * 嗨 20.23 * ** * ** * ** * ** * ** * ** * */

+0

谢谢。一次只传递一个结构时效果很好。原来的功能是传递一个大小为“size”的数组,我认为这是行不通的。我创建了一个新的函数,只返回我需要的索引处的结构。 – diditexas