如何从C#中的非托管内存中读取?

Ben*_*Ben 5 c# c++ interop unmanaged

我想用C++创建Foo的非托管数组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;
}
Run Code Online (Sandbox Code Playgroud)

在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);
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何从中检索对象IntPtr detectedFoos.它应该可能以某种方式...任何提示?

UPDATE

我们假设,Foo是一个简单的检测矩形.

C++:

struct Foo
{
    int x;
    int y;
    int w;
    int h;
};
Run Code Online (Sandbox Code Playgroud)

C#:

[StructLayout(LayoutKind.Sequential)]
public struct Foo
{
    public int x;
    public int y;
    public int width;
    public int height;
}
Run Code Online (Sandbox Code Playgroud)

是否可以在释放非托管内存之前从非托管内存中读取并从中创建新的托管对象?

我不知道如何Foo检测到对象,所以我不知道,在调用C#之前要分配多少内存detectFoo().这就是为什么我在C++中分配/释放内存并只是传递一个指向它的指针.但不知怎的,我无法detectedFoo在C#下检索s指针地址.我怎么做?

Ben*_*Ben 0

我最终通过使用 C++/CLI 包装类解决了我的问题。