高手们好,我才用C#不久,用到一个C++编写的动态库,在动态库的接口中含有结构类型的参数。
对于由简单数据类型构成的结构类型参数,我已经调用成功了,但有的结构参数里面含有数组,使用的时候报出不支持异常。
比如一个简单的代码如下:
C++代码:
struct stru1 //结构类型
{
int x;
int y;
int xx[2];
}int add(stru1 stru) //动态库中函数,已在其函数声明中作为外部接口
{
return x+y+xx[0]++xx[1];
}C#中代码:
...
public struct stru1
{
public int x;
pubilc int y;
public int[] xx;
}
...
[DllImport("TestDll.dll")]
unsafe public static extern int add(stru1 stru);
...
/* 调用动态库 */
stru1 stru;
stru.xx = new int[2];
stru.x = 2;
stru. y = 3;
stru.xx[0] = 10;
stru.xx[1] = 11;
add(stru); //执行到此会报不支持异常
对于由简单数据类型构成的结构类型参数,我已经调用成功了,但有的结构参数里面含有数组,使用的时候报出不支持异常。
比如一个简单的代码如下:
C++代码:
struct stru1 //结构类型
{
int x;
int y;
int xx[2];
}int add(stru1 stru) //动态库中函数,已在其函数声明中作为外部接口
{
return x+y+xx[0]++xx[1];
}C#中代码:
...
public struct stru1
{
public int x;
pubilc int y;
public int[] xx;
}
...
[DllImport("TestDll.dll")]
unsafe public static extern int add(stru1 stru);
...
/* 调用动态库 */
stru1 stru;
stru.xx = new int[2];
stru.x = 2;
stru. y = 3;
stru.xx[0] = 10;
stru.xx[1] = 11;
add(stru); //执行到此会报不支持异常
希望高手们能指点下,我才用c#
做的是一个智能手持设备上的东东
C#中代码:
...
[StructLayout(LayoutKind.Sequential)] <-- 莫非是这个没加的原因
public struct stru1
{
不知道是不是这个原因,明天我加上试试,先谢谢Dobzhansky
{
int x;
int y;
int xx[2];
};__declspec(dllexport) int __stdcall
add(struct stru1 stru)
{
return stru.x+stru.y+stru.xx[0]+stru.xx[1];
}
c# 调用:using System.Runtime.InteropServices;
namespace a
{
class b
{
static void Main()
{
System.Console.WriteLine("c");
stru1 stru;
stru.xx = new int[2];
stru.x = 2;
stru. y = 3;
stru.xx[0] = 10;
stru.xx[1] = 11;
int result = add(stru); //执行到此会报不支持异常
System.Console.WriteLine(result);
}
[DllImport("c.dll", EntryPoint = "_add@16")] // <- 关键
public static extern int add(stru1 stru);
// [StructLayout(LayoutKind.Sequential)]
public struct stru1
{
public int x;
public int y;
public int[] xx;
}
}
}
不过还是很感谢Dobzhansky的热心帮助!!
[StructLayout(LayoutKind.Sequential)]
public struct stru1
{
public int x;
public int y;
[MarshalAs(UnmanagedType.ByValArray,SizeConst = 2)]
public int[] xx1;
}