【发布时间】:2020-04-21 15:56:28
【问题描述】:
我正在尝试将 ObjectiveC/C++ 创建的带有字符串的结构数组编入 C#,但我没有成功。大多数时候 C# 编组找不到“值”字符串字段。这是我目前为止最好的:
C#结构:
private struct Entry
{
public string Key;
public string Value;
}
C#代码
public Dictionary<string, string> Convert()
{
var dic = new Dictionary<string, string>();
getEntries(NativeInstance, out IntPtr pUnmanagedStringArray, out int keysCount);
IntPtr[] pIntPtrArray = new IntPtr[keysCount];
Entry[] entriesInDictionary = new Entry[keysCount];
// I'm not really sure I've done this correctly?
Marshal.Copy(pUnmanagedStringArray, pIntPtrArray, 0, keysCount);
for (int i = 0; i < keysCount; i++)
{
Debug.Log("Iter " + i);
// I'm not really sure I've done this correctly?
entriesInDictionary[i] = Marshal.PtrToStructure<Entry>(pIntPtrArray[i]);
}
Marshal.FreeHGlobal(pUnmanagedStringArray); // Free native malloc for array
foreach (var entry in entriesInDictionary)
{
Debug.Log("Entry" + entry.Key);
Debug.Log("Value" + entry.Value);
//dic.Add(entry.key, entry.value);
}
return dic;
}
C++/ObjectiveC
struct Entry {
const char* key;
const char* value;
};
void getEntries(NSDictionary* dictionary, const Entry* &_entries, int &size) {
int count = (int) [dictionary count];
Entry* entries = (Entry*) malloc(count * sizeof(Entry) );
int i = 0;
for(id key in dictionary) {
id value = [dictionary objectForKey:key];
entries[i].key = Utils::mallocCharStr(key); // malloc char* from NSString.
entries[i].value = Utils::mallocCharStr(value); // malloc char* from NSString.
++i;
}
_entries = entries;
size = count;
}
此时我非常迷茫,我尝试了不同的组合。我也为这两个字符串尝试了一个 IntPtr 结构,但我确定“值”指针为 0。
有什么想法吗?
【问题讨论】:
-
你的统一版本是什么?
-
最新的。所以2019.3。
标签: c# c++ objective-c unity3d marshalling