日期:2014-05-19  浏览次数:21175 次

C# 传结构体数组到C++dll中
C++   dll   的参数里有一个结构体数组,是以指针给出的。C#怎么传递

------解决方案--------------------
C#需要声明
类似
从 Kernel32.dll 导出的 GetSystemTime。
VOID GetSystemTime(LPSYSTEMTIME lpSystemTime);
传递到该函数的初始结构包含以下元素:
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;
在该示例中,SystemTime 类包含表示为类成员的原始结构的元素。StructLayoutAttribute 属性经过设置,以确保成员在内存中按它们的出现顺序依次排列。
LibWrap 类包含 GetSystemTime 方法的托管原型,默认情况下,它将 SystemTime 类作为 In/Out 参数进行传递。必须用 InAttribute 和 OutAttribute 属性声明该参数,因为作为引用类型的类在默认情况下将作为输入参数进行传递。为使调用方接收结果,必须显式应用这些方向属性。App 类创建 SystemTime 类的一个新实例,然后访问其数据字段。
声明原型
[Visual Basic]
' Declares a class member for each structure element.
< StructLayout(LayoutKind.Sequential )> _
Public Class SystemTime
Public year As Short
...
Public milliseconds As Short
End Class 'SystemTime

Public Class LibWrap
' Declares a managed prototype for the unmanaged function.
Declare Sub GetSystemTime Lib "Kernel32.dll " ( <[In], Out> ByVal st _
As SystemTime )
End Class 'LibWrap
[C#]
// Declares a class member for each structure element.
[ StructLayout( LayoutKind.Sequential )]
public class SystemTime
{
public ushort year;
...
public ushort milliseconds;
}

public class LibWrap
{
// Declares a managed prototype for the unmanaged function.
[ DllImport( "Kernel32.dll " )]
public static extern void GetSystemTime( [In,Out] SystemTime st );
}
调用函数
[Visual Basic]
Public Class App
Public Shared Sub Main()
Dim st As New SystemTime()
LibWrap.GetSystemTime( st )
Console.Write( "The Date and Time is: " )
...
End Sub 'Main
End Class 'App
[C#]
public class App
{
public static void Main()
{
SystemTime st = new SystemTime();
LibWrap.GetSystemTime( st );
Console.Write( "The Date and Time is: " );
...
}
}

------解决方案--------------------
IntPtr Add([MarshalAs(UnManagedType.LPArray)]Struct_data[] datatag,int num);
------解决方案--------------------
MARK
学习
------解决方案--------------------
再给你一段代码,直接抄msdn的
[ StructLayout( LayoutKind.Sequential )]
public struct MyPoint
{
public int x;
public int y;
public MyPoint( int x, int y )
{
this.x = x;
this.y = y;
}
}
[ StructLayout( LayoutKind.Sequential, CharSet=CharSet.Ansi )]
public struct MyPerson
{
public String first;
public String last;
public MyPerson( String first, String last )
{
this.first = first;
this.last = last;
}
}

public class LibWrap
{
// Declares a managed prototype for an array of integers by value.
// The array size cannot be changed, but the array is copied back.
[ DllImport( "..\\LIB\\PinvokeLib.dll " )]
public static extern int TestArrayOfInts([In, Out] int[] array, int size );

// Declares a managed prototype for an array of integers by reference.
// The array size can change, but the array is not copied back