How can I read from unmanaged memory in C #?

I would like to create objects Fooin C # from an unmanaged array of structures Foocreated in C ++. Here is how I think it should work:

On the C ++ side:

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;
}

On the side of C #: (I missed some fancy code that allows you to call C ++ functions from within C # for better readability);

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);
}

But I do not know how to get objects from IntPtr detectedFoos. It should be possible somehow ... Any clues?

UPDATE

Suppose Foo- this is a simple detection rectangle.

C ++:

struct Foo
{
    int x;
    int y;
    int w;
    int h;
};

WITH#:

[StructLayout(LayoutKind.Sequential)]
public struct Foo
{
    public int x;
    public int y;
    public int width;
    public int height;
}

Can I read from unmanaged memory and create new managed objects from it before releasing unmanaged memory?

, Foo, , # detectFoo(). / ++ . - detectedFoo #. ?

+5
3

, ++/CLI.

0

Foo #. , Foo sizeof(Foo), System.Runtime.Interopservices.Marshal.PtrToStructure() Foo .

+2

#, stuct. blitable ( # ave , C)

" "

Or post your real "Foo" structure and I can show you the C # version

UPDATE:

Since your structure seems fuzzy, you can simply direct the pointer to unmanaged memory to the pointer to the structure defined in C #:

If it’s convenient for you to use unsafe code, you can write:

unsafe List<Foo> detectFooObjects()
{
 List<Foo> res = new List<Foo>()
IntPtr fooDetector = createFooDetector();

IntPtr detectedFoos = IntPtr.Zero;
int nNumFoos = detectFoo(fooDetector, ref detectedFoos );
for(int i=0;i<nNumFoos;i++)
{
   Foo** ppDetectedFoos = detectedFoos.ToPointer();

   Foo* pFoo = *ppDetectedFoos
   res.Add(*pFoo); //copies the struct because is a struct
   ppDetectedFoos++:
}

releaseFooObjects(detectedFoos);

releaseFooDetector(fooDetector);
return res;
}
0
source

All Articles