将intptr转换为ulong数组

本文关键字:ulong 数组 转换 intptr | 更新日期: 2023-09-27 18:02:13

我正在从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;
}

如何从IntPtr中读取ulong数组

将intptr转换为ulong数组

虽然Marshal类不提供直接处理ulong s的任何方法,但确实为您提供了Marshal.Copy(IntPtr, long[], int, int),您可以使用long数组,然后将值转换为ulong s。

以下内容适合我:

[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);
}

考虑只使用不安全代码:

IntPtr pfoo = ph_dct_videohash(/* args */);
unsafe {
    ulong* foo = (ulong*)pfoo;
    ulong value = *foo;
    Console.WriteLine(value);
}