How to pass the address of objects created in C # List in C ++ dll?

I searched all over Google to find answers to my questions, but I don’t quite understand what I found. I have some objects that are created and stored in a C # list after using System.IO to read some text files. After that, I want to send links (using constant pointers) to each of these objects to inner classes in the C ++ dll so that it can use them to calculate some algorithms.

Here is a simple example (not actual code) of what I am doing:

C # Class:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class SimpleClass
{
    [MarshalAs(UnmanagedType.LPStr)]
    public string           Name;
    public float            Length;
}

with the corresponding line C:

struct SimpleClass
{
    const char* Name;
    float Length;
};

stored in

List<SimpleClass> ItemList;

after parsing some text files.

Then call the following dll function:

WITH#:

[DllImport("SimpleDLL")]
public static extern void AddSimpleReference(SimpleClass inSimple);

WITH

void AddSimpleReference(const SimpleClass* inSimple)
{
   g_Vector.push_back(inSimple); // g_Vector is a std::vector<const SimpleClass* > type
}

I tried:

for(int i=0; i<ItemList.Count;++i)
{
    SimpleClass theSimpleItem = ItemList[i];
    AddSimpleReference(theSimpleItem);
}

, / , # , , ++ ( temp) . ++ DLL, #?

UPDATE: , . , # script Unity, .

+3
3

interop, ( ).

[DllImport("SimpleDLL")]
public unsafe static extern void AddSimpleReference(SimpleClass* inSimple);

, GC , , . fixed:

SimpleClass theSimpleItem = ItemList[i];
unsafe
{
    fixed(SimpleClass* ptr = &theSimpleItem)
    {
        AddSimpleReference(ptr);
    }
}

, AddSimpleReference , . std::vector . , , , - , GC - , fixed.

, , . GCHandle.

// Change the interop signature, use IntPtr instead (no "unsafe" modifier)
[DllImport("SimpleDLL")]
public static extern void AddSimpleReference(IntPtr inSimple);

// ----
for(int i=0; i<ItemList.Count;++i)
{
    SimpleClass theSimpleItem = ItemList[i];
    // take a pinned handle before passing the item down.
    GCHandle handle = GCHandle.Alloc(theSimpleItem, GCHandleType.Pinned);
    AddSimpleReference(GCHandle.ToIntPtr(handle));
    // probably a good idea save this handle somewhere for later release
}

// ----
// when you're done, don't forget to ensure the handle is freed
// probably in a Dispose method, or a finally block somewhere appropriate
GCHandle.Free(handle);

- , , - , .

+6

, , . - MSDN.

fixed , , .

+1

. # GC . .

0

All Articles