C#p/调用C方法返回一个字节* [英] C# p/invoke C method returning a byte*

查看:110
本文介绍了C#p/调用C方法返回一个字节*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C dll,其中一个功能具有以下签名:

I got a C dll where one of the functions has the following signature:

DLLExport byte* DecodeData(CDecoderApp* decoderApp, HWND handle, byte* data, int length, int* frameLength, int* waveDataLength, int* decodedFrameSize, int* channels, int* frequency)

我需要p/调用此方法并尝试以下操作:

I need to p/invoke this method and tried the following:

[DllImport("Decoder.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern byte[] DecodeData(IntPtr decoderApp, IntPtr handle, byte[] data, int length, out int frameLength, out int waveDataLength, out int decodedFrameSize, out int channels, out int frequency);

这是行不通的,因为我猜c#不知道字节数组的大小.

Which doesn't work as I guess that c# doesn't know the size of the byte array.

我应该如何解决这个问题,以便获得返回的字节数组?

How should I solve this so I can get the returned byte array ?

推荐答案

编组器不能像您怀疑的那样编组类型为byte[]的返回值.您将需要自己进行编组.将返回值更改为IntPtr类型:

The marshaller cannot, as you suspect, marshal a return value of type byte[]. You will need to do the marshalling yourself. Change the return value to be of type IntPtr:

[DllImport("Decoder.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr DecodeData(
    IntPtr decoderApp, 
    IntPtr handle, 
    byte[] data, 
    int length, 
    out int frameLength, 
    out int waveDataLength, 
    out int decodedFrameSize, 
    out int channels, 
    out int frequency
);

像这样调用函数:

IntPtr decodedDataPtr = DecodeData(...);

检查错误:

if (decodedDataPtr == IntPtr.Zero)
    // handle error

大概是参数之一,也许waveDataLength包含返回的字节数组的长度:

Presumably one of the parameters, perhaps waveDataLength contains the length of the byte array that is returned:

byte[] decodedData = new byte[waveDataLength];
Marshal.Copy(decodedDataPtr, decodedData, 0, waveDataLength);

当然,现在您只剩下一个指向非托管代码分配的内存的指针.您将需要找到一种方法来释放该内存.也许内存是在共享堆上分配的.也许非托管代码会导出一个解除分配器.但是利用我们所拥有的信息,我们无法确切地告诉您如何对其进行分配.

Of course, now you are left holding a pointer to memory that the unmanaged code allocated. You will need to find a way to deallocate that memory. Perhaps the memory is allocated on a shared heap. Perhaps the unmanaged code exports a deallocator. But with the information that we have, we cannot tell you precisely how to deallocate it.

这篇关于C#p/调用C方法返回一个字节*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆