C# 跨dll将列表中结构的引用从托管代码传递到非托管代码
我对C非常陌生,目前在dll中将结构编组到C函数时遇到一些问题。所讨论的结构在C中包含几个int、float和一个char*,如下所示:C# 跨dll将列表中结构的引用从托管代码传递到非托管代码,c#,pointers,struct,marshalling,unmanaged,C#,Pointers,Struct,Marshalling,Unmanaged,我对C非常陌生,目前在dll中将结构编组到C函数时遇到一些问题。所讨论的结构在C中包含几个int、float和一个char*,如下所示: struct Bin { char* m_name; float m_start; float m_end; int m_OwnerID; int m_SelfID; } 对应的C结构定义,我认为应该是: public struct Bin { public string m_name; public
struct Bin
{
char* m_name;
float m_start;
float m_end;
int m_OwnerID;
int m_SelfID;
}
对应的C结构定义,我认为应该是:
public struct Bin
{
public string m_name;
public float m_start;
public float m_end;
public int m_OwnerID;
public int m_SelfID;
}
我还在C中实现了一个解析器/读取器函数,它读取一个文本文件,创建Bin对象并将它们存储在一个列表对象中,列表对象是主应用程序类的一个类成员。同时,我想通过Dll函数调用将列表中的每个结构对象引用给非托管C++类,这样它可以在其他函数调用期间引用,而不需要在非托管端复制数据。p>
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();
}
<>在C++ DLL端,一个全局C++类对象在STD::vector容器中存储指向每个结构的指针:
BinManager theBinManager;
void PassBinPtrIn(Bin* theBin)
{
theBinManager.AddBin(theBin);
}
void BinManager::AddBin(Bin* theBin)
{
m_BinPtrList.push_back(theBin);//a std::vector<Bin*> type
}
但是,在编写passptrstoc库sharo函数时,我面临一些问题。在将Bin结构添加到列表中之后,我永远无法获得列表中Bin的实际指针或引用。我尝试了Marshall.StructureToPtr,但它总是使我的应用程序崩溃。我还了解到,很难将struct中的托管字符串作为指针/引用传递到C代码中。关于如何解决这个问题,请给我一些帮助或建议。感谢您阅读这篇冗长的文章