Pass reference of struct in a list from managed to unmanaged code across dll
I am very new to C# and currently having some trouble with marshalling structs to C functions in a dll. The struct in question contains a few ints, float and one char* in C as follows:
struct Bin
{
char* m_name;
float m_start;
float m_end;
int m_OwnerID;
int m_SelfID;
}
The corresponding C# struct defintion, I think should be:
public struct Bin
{
public string m_name;
public float m_start;
public float m_end;
public int m_OwnerID;
public int m_SelfID;
}
I also implemented a parser/reader function in C# that reads a text file, creates the Bin objects and stores them in a List object, which is a class member of the main app class. At the same time, I want to pass references to each struct object in the list to a unmanaged C++ Class through a Dll function call so it can be referred to during other function calls without the need to duplicate data on the unmanaged side.
class ProgramMain
{
public List<Bin> m_BinList;
static void Main()
{
//Some functions calls
//Fills up List<Bin>
LoadBinData(string inFile);
//Iterate each bin in list and pass reference to each bin to C++ class via
//Dll Imported function
PassPtrsToLibrary(); //???
}
public void LoadBinData(string inFile)
{
.....
}
public void PassPtrsToLibrary()
{
????
}
/* PassByReferenceIn */
[DllImport ("mylib")]
public static extern
void PassBinPtrIn(ref Bin theBin);
//Some other function that reads the stored Bin pointers' data and perform calculations
[DllImport ("mylib")]
public static extern
int ProcessBin();
}
On the C dll side, internally a global C++ class object stores the pointer to each struct in a std::vector container:
BinManager theBinManager;
void PassBinPtrIn(Bin* theBin)
{
theBinManager.AddBin(theBin);
}
void BinManager::AddBin(Bin* theBin)
{
m_BinPtrList.push_back(theBin);//a std::vector<Bin*> type
}
However I am facing some problems when writing the PassPtrsToLibrary() C# sharo function. After adding the Bin struct into the list, I can never get the actual pointer or reference to the bin inside the list. I have tried Marshall.StructureToPtr but it always crash my application. 开发者_如何学CI also read that it is difficult to pass a managed string in struct as pointer/reference into C code. Please give me some help or advice as how to solve this problem. Thank you for reading this lengthy post.
精彩评论