2014-08-27 177 views
1

我有一个C++ .DLL和C#应用程序。在DLL我有这样一个功能:从int []转换为int *

namespace Sample { public ref class SampleClass { public: int f(int arr[], int length); }; }

我怎样才能把它从C#应用程序?问题是在C++中,我只能使用int*参数,并且不能声明int[],并且在c#中只能使用int[]变量。

我曾尝试申报在C#中int*[]型,但由于

是不可能的不能拿一个管理型

错误的地址。我不知道如何将数组放入此函数。

UPD: 努力的DllImport像

[DllImport("samplelib.fll", EntryPoint = "Sample.SampleClass.f")] 

,但似乎是错误的。

+0

为什么你甚至在C++是签名?你怎么知道'arr'中有多少个元素? – crashmstr 2014-08-27 12:14:12

+0

DllImport to ...只需将int和[]导入并签名即可。请参阅MSDN上的示例。 – 2014-08-27 12:14:52

+2

@crashmstr'int f(int arr [])'与C++中的int f(int arr *)'相同。 []语法就在那里混淆。 – juanchopanza 2014-08-27 12:16:33

回答

0

我不确定,如果这是你想要的。您的例子似乎在有点不完整......

比方说,你有这样的事情在C/C++:

void TakesAnArray(int size, int array[]) { 
    printf_s("[unmanaged]\n"); 
    for (int i=0; i<size; i++) 
     printf("%d = %d\n", i, array[i]); 
} 

然后你想从C#北京时间电话,让您创建一个包装类。

internal static class NativeMethods 
{ 
    [DllImport("SomeLib.dll")] 
    public static extern void TakesAnArray(int size, [In, Out] int[] array); 
} 
+0

谢谢,那有效。但是我找不到入口点的正确语法。我正在尝试Sample.SampleClass.f,但这并不奏效。 – AndrewR 2014-08-27 13:33:13

+0

@ maniac98066如何找到C++ .DLL的入口点并使用它:http://stackoverflow.com/a/12885084/3908097 – Rimas 2014-08-27 14:51:44

0
int[] arr = new int[10]; 
int ptrsize = arr.Length * Marshal.SizeOf(typeof(int)); 
IntPtr arrptr = Marshal.AllocHGlobal(ptrsize); 
Marshal.Copy(arr, 0, arrptr, ptrsize); 
NativeFunction(arr.Length, arrptr); 
//after 
Marshal.FreeHGlobal(arrptr); 

使用数组的指针

void NativeFunction(int length, int* array) { /*...*/ } 

导入(\\是可执行文件的路径)

[DllImport(".\\MyLib.dll")] 
static extern void NativeFunction(int length, IntPtr array); 
+0

您确定要使用数组的内存大小而不是传入的元素数C++函数? – crashmstr 2014-08-27 12:40:30

+0

@crashmstr是的,你是正确的与长度固定 – Sam 2014-08-27 12:42:54

+0

-1:这个代码已经比使用一个适当的P/Invoke签名更复杂,并没有处理释放内存的所有例外情况下,一个适当的签名将为您处理它。 – 2014-08-27 12:54:38