我希望您能够从C++创建的未托管的
在C++方面:
在C#方面: (我省略了一些花哨的代码,以便更好地从C#中调用C ++函数);
但我不知道如何从
更新:假设
C++:
C#:
Foo
结构体数组中,翻译出与C#相关的内容。以下是我的想法:在C++方面:
extern "C" __declspec(dllexport) void* createFooDetector()
{
return new FooDetector();
}
extern "C" __declspec(dllexport) void releaseFooDetector(void* fooDetector)
{
FooDetector *fd = (FooDetector*)fooDetector;
delete fd;
}
extern "C" __declspec(dllexport) int detectFoo(void* fooDetector, Foo **detectedFoos)
{
FooDetector *fd = (FooDetector*)fooDetector;
vector<Foo> foos;
fd->detect(foos);
int numDetectedFoos = foos.size();
Foo *fooArr = new Foo[numDetectedFoos];
for (int i=0; i<numDetectedFoos; ++i)
{
fooArr[i] = foos[i];
}
detectedFoos = &fooArr;
return numDetectedFoos;
}
extern "C" __declspec(dllexport) void releaseFooObjects(Foo* fooObjects)
{
delete [] fooObjects;
}
在C#方面: (我省略了一些花哨的代码,以便更好地从C#中调用C ++函数);
List<Foo> detectFooObjects()
{
IntPtr fooDetector = createFooDetector();
IntPtr detectedFoos = IntPtr.Zero;
detectFoo(fooDetector, ref detectedFoos);
// How do I get Foo objects from my IntPtr pointing to an unmanaged array of Foo structs?
releaseFooObjects(detectedFoos);
releaseFooDetector(fooDetector);
}
但我不知道如何从
IntPtr detectedFoos
中检索对象。应该有一种方法... 有什么提示吗?更新:假设
Foo
是一个简单的检测矩形。C++:
struct Foo
{
int x;
int y;
int w;
int h;
};
C#:
[StructLayout(LayoutKind.Sequential)]
public struct Foo
{
public int x;
public int y;
public int width;
public int height;
}
能否在释放非托管内存之前从非托管内存中读取并创建新的托管对象?
我不知道有多少个Foo
对象会被检测到,因此在调用detectFoo()
之前无法确定在C#中分配多少内存。这就是为什么我在C++中分配/释放内存并只传递指针的原因。但是在C#下,我无法检索到detectedFoo
指针地址。我该怎么做?