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

标签 c# c++ interop unmanaged

我想在 C# 中从在 C++ 中创建的 Foo 结构的非托管数组创建 Foo 对象。 这就是我认为它应该工作的方式:

在 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 的指针地址。我该怎么做?

最佳答案

您必须在 C# 项目中重新声明 Foo。假设您知道 Foo 的计数和 sizeof(Foo) 的值,您应该能够使用 System.Runtime.Interopservices.Marshal.PtrToStructure() 一次检索一个 Foo 结构。

关于c# - 如何从 C# 中的非托管内存中读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12202334/

相关文章:

c# - 继承时使用基类

c# - mysql : using BETWEEN in table?

c++ - 在 opengl 中渲染迷宫

c++ - 我无法理解二维模数 C++

C# - Hook 到现有的 COM 对象

c# - 排序列表<List<MyType>>

c# - 继承 Controller 时无法让 Route 在 ASP.Net Web API 2 中工作

c++ - CGAL union 误解

c# - 以编程方式将 Doc 转换为 Docx bug

c# - 使用 P/Invoke 编码双参数