2

我正在从 C# 调用一个方法,如下所示:

[DllImport(@"pHash.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr ph_dct_videohash(string file, ref int length);

这是我从图书馆调用的方法

ulong64* ph_dct_videohash(const char *filename, int &Length){

    CImgList<uint8_t> *keyframes = ph_getKeyFramesFromVideo(filename);
    if (keyframes == NULL)
        return NULL;

    Length = keyframes->size();

    ulong64 *hash = (ulong64*)malloc(sizeof(ulong64)*Length);
    //some code to fill the hash array
    return hash;
}

如何ulong从 中读取数组IntPtr

4

2 回答 2

2

虽然Marshal该类没有提供任何ulong直接处理 s 的方法,但它确实为您提供Marshal.Copy(IntPtr, long[], int, int)了可用于获取long数组然后将值转换为ulongs 的方法。

以下对我有用:

[DllImport("F:/CPP_DLL.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
static extern IntPtr uint64method(string file, ref int length);

static ulong[] GetUlongArray(IntPtr ptr, int length)
{
    var buffer = new long[length];
    Marshal.Copy(ptr, buffer, 0, length);
    // If you're not a fan of LINQ, this can be
    // replaced with a for loop or
    // return Array.ConvertAll<long, ulong>(buffer, l => (ulong)l);
    return buffer.Select(l => (ulong)l).ToArray();
}

void Main()
{
    int length = 4;
    IntPtr arrayPointer = uint64method("dummy", ref length);
    ulong[] values = GetUlongArray(arrayPointer, length);
}
于 2015-07-10T20:54:09.027 回答
2

考虑只使用不安全的代码:

IntPtr pfoo = ph_dct_videohash(/* args */);
unsafe {
    ulong* foo = (ulong*)pfoo;
    ulong value = *foo;
    Console.WriteLine(value);
}
于 2015-07-10T20:59:22.810 回答