【发布时间】:2017-05-02 17:01:18
【问题描述】:
我遇到了 C++ Dll 与 Unity 集成的问题。我在网上找到了一些代码(文章末尾的链接),但它不起作用。
这是我的 C++ DLL 代码(我想向统一发送一个包含一些要点的结构):
struct Pontos {
int i;
float f;
};
Pontos **pontos;
DllExport bool SetPoints(Pontos *** a, int *i)
{
pontos = new Pontos*[4];
for (int j = 0; j < 4; j++) {
pontos[j] = new Pontos; // Actually create each object.
pontos[j]->i = j;
pontos[j]->f = (float)j;
}
*a = pontos;
*i = 4;
return true;
}
从统一代码中,我得到以下错误:
文件中没有 MonoBehaviour 脚本,或者它们的名称与文件名不匹配
我不知道这是什么意思。 在这里,我尝试获取这些点并将它们保存在 c# 中:
[DllImport("dll")]
private static extern bool SetPoints(out IntPtr ptrResultVerts, out int resultVertLength);
public struct Pontos
{
int i;
float f;
};
void Start()
{
IntPtr ptrNativeData = IntPtr.Zero;
int itemsLength = 0;
bool success = SetPoints(out ptrNativeData, out itemsLength);
if (!success)
{
return;
}
Pontos[] SArray = new Pontos[itemsLength]; // Where the final data will be stored.
IntPtr[] SPointers = new IntPtr[itemsLength];
Debug.Log("Length: " + itemsLength); // Works!
Marshal.Copy(ptrNativeData, SPointers, 0, itemsLength); // Seems not to work.
for (int i = 0; i < itemsLength; i++)
{
Debug.Log("Pointer: " + SPointers[i]);
SArray[i] = (Pontos)Marshal.PtrToStructure(SPointers[i], typeof(Pontos));
}
我从Can't marshal array of stucts from C++ to C# in Unity 得到这个代码。
【问题讨论】:
-
你忘了把
[StructLayout(LayoutKind.Sequential),Serializable]放在public struct Pontos的顶部.... -
仅在 c++ 中还是需要在 c# 中做其他事情?
-
阅读一些文章我发现Marshalling不需要序列化
-
当(行为)文件中的第一个类型不具有相同名称时,会出现“文件中没有 MonoBehaviour 脚本,或者它们的名称与文件名不匹配”,请尝试移动其他类型,例如
Pontos到不同的文件。应该有魅力。