C++部分:
WIN32LIB_API double* range(double* res)
{
int x;
int y;
//sizeof 得到元素个数,并非数组长度 从大到小排列
for(int i=0;i<3;i++)
{
x=res[i];
for(int j=i+1;i<3;j++)
{
if(x>res[j])
{
x=res[j];
res[j]=res[i];
res[i]=x;
}
}
}
return res;
C# 引用部分
[DllImport(@"C:\Users\xnguo\Documents\Visual Studio 2010\Projects\Csharp封装C++\Debug\win32Lib.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
public static extern double[] range([MarshalAs (UnmanagedType.LPArray ,SizeParamIndex =0)]double [] x);
C#中调用range时抛出异常Cannot marshal 'return value': Invalid managed/unmanaged type combination.
求大神帮我把这快代码调试出来能运行
[DllImport(@"C:\Users\xnguo\Documents\Visual Studio 2010\Projects\Csharp封装C++\Debug\win32Lib.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
[return:MarshalAs (UnmanagedType.LPArray ,SizeConst=3)]
public static extern double[] range([MarshalAs (UnmanagedType.LPArray ,SizeConst=3)]double [] x);
不行啊 还是抛异常 和以前一样
为什么要return呢?这个返回值应该就是输入值吧。而且这里返回意味着在C++里面分配内存,在C#里使用,可能会有问题。
如果一定要return,可以用传引用值的方法,
比如 range(double [] x, ref double[] out);
用指针来写,很方便
unsafe public static extern double* range(double* x);
调用的时候用fixed
这样:
double[] ds= new double[18];
fixed (double* dd = ds)
{
range(dd);
}
大神不行啊 抛异常Attempted to read or write protected memory. This is often an indication that other memory is corrupt
@郭小宁:
是你这个C++函数本身有错误,不知道你想干什么!