我正在尝试(过去10个小时.... grr)使这个东西工作,但到目前为止,无论我尝试了什么 - 它拒绝:)
基本上我正在为某人做一个忙 - 我的力量不是Windows / .NET编码肯定的,我试图用我已经拥有的东西修补一些代码。
有什么问题?
我正在尝试调用一个C DLL库方法,将一个2d结构数组返回给c#。
但似乎我在如何从c#中读取数据方面做错了。
我开发了一个简单的C控制台应用程序,我从那里调用DLL - 一切都很好 - 没有任何问题。只有c#失败了!
以下是该方法的C实现:
int get_available_devices(idevice_info_t **devices, uint32_t *count) {
char **dev_list = NULL;
char *dev_name = NULL;
int i, total_devices;
if (idevice_get_device_list(&dev_list, &total_devices) < 0) {
fprintf(stderr, "ERROR: Unable to retrieve device list!\n");
return -1;
}
idevice_info_t *tmpArr = (idevice_info_t*)calloc(total_devices, sizeof(idevice_info));
int ii = 0;
int res_name = 0;
idevice_info_t dtmp = NULL;
for (i = 0; i <= total_devices - 1; i++) {
res_name = idevice_get_device_name(dev_list[i], &dev_name);
dev_name = (res_name == 0 ? dev_name : "");
printf("%s: %s\n", dev_name, dev_list[i]);
dtmp = (idevice_info_t)malloc(sizeof(struct idevice_info));
strncpy_s(dtmp->udid, sizeof dtmp->udid - 1, dev_list[i], sizeof dtmp->udid - 1);
strncpy_s(dtmp->name, sizeof dtmp->name - 1, dev_name, sizeof dtmp->name - 1);
tmpArr[i] = dtmp;
}
idevice_device_list_free(dev_list);
*devices = tmpArr;
*count = total_devices;
return 0;}
以下是我在c#方面所做的事情:
[DllImport(LIBNAME, CallingConvention = CallingConvention.Cdecl)]
static public extern short get_available_devices(out IntPtr devices, out uint count);
public static Dictionary<string, string> getAvailableDevices()
{
IntPtr p = IntPtr.Zero;
Dictionary<string, string> ret = null;
uint totalDevices = 0;
int res = External.get_available_devices(out p, out totalDevices);
if (res != 0 || totalDevices < 1)
{
return null;
}
ret = new Dictionary<string, string>();
External.idevice_info ppStruct;
int sSize = Marshal.SizeOf(typeof(External.idevice_info));
for (int i = 0; i <= totalDevices - 1; i++)
{
p = (IntPtr)Marshal.PtrToStructure(p, typeof(IntPtr));
ppStruct = (External.idevice_info)Marshal.PtrToStructure(p, typeof(External.idevice_info));
ret.Add(ppStruct.udid, ppStruct.name);
p = new IntPtr(p.ToInt64() + sSize);
}
return ret;
}
实际问题是什么?
一旦我到达for循环()的第二次迭代,我就会遇到访问冲突:
An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll
我想我没有正确计算指针但是......我真的尝试了很多不同的场景,没有任何作用。
HELP! :)
答案 0 :(得分:1)
您正在p
取消引用p = (IntPtr)Marshal.PtrToStructure(p, typeof(IntPtr));
,然后在尝试增加时结束时,所有地狱都会崩溃。
使用新的本地,以便不会连续取消引用原始指针。
例如:
for (int i = 0; i <= totalDevices - 1; i++)
{
IntPtr pp = (IntPtr)Marshal.PtrToStructure(p, typeof(IntPtr));
ppStruct = (External.idevice_info)Marshal.PtrToStructure(pp,
typeof(External.idevice_info));
ret.Add(ppStruct.udid, ppStruct.name);
p += sSize; // easier, does the same :)
}