从C#将byte []传递到C ++ [英] passing byte[] to C++ from C#

查看:106
本文介绍了从C#将byte []传递到C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google上搜索了很多,但没有帮助.

我的C#应用​​程序中有一个已知大小的byte []类型的音频缓冲区.

I have googled a lot but of no help.

I have an audio buffer of type byte[] of known size in my C# appication.

public int processAudioBuffer(Byte[] buffer, int bufferSize)
{
//need to call the C++/CLI function ProcessBuffer()
}


我有一个C ++/CLI dll,它使用此缓冲区并将其传递给本机代码


I have a C++/CLI dll which takes this buffer and pass it to the native code

ProcessBuffer(unsigned short* buffer, int buffersize);


即使此函数是托管类型,出于特定原因,我也必须将参数类型保持为unsigned short *.

我只有自由在C#中做任何可以将此缓冲区传递给C ++函数的自由.

无论我做什么,编译器总是以
结尾


Even though this function is managed type, for specific reasons I have to keep the parameter type as unsigned short*.

I only have freedom to do whatever I can in C# to pass this buffer to the C++ function.

No matter what I do, the compiler always ends up with

"Cannot convert System.xxxx to ushort*"
"Overloaded method ProcessBuffer(ushort*, int) has some invalid arguements"


任何帮助深表感谢.谢谢!


Any help is much appreciated. Thanks!

推荐答案

unsigned short在C ++中为16位,而byte 为8位.因此,您不能混合和匹配它们并期望一切正常(当使用指针时).在您的C#代码中,使用ushort ,您应该可以.这是一个快速而肮脏的未经测试的示例:

unsigned short in C++ is 16 bits whereas byte is 8 bits. So you cannot mix and match them and expect everything to work (when you are using pointers). In your C# code, use ushort and you should be okay. Here''s a quick and dirty untested example:

public ref class MyClass
{
public:
  void ProcessBuffer(unsigned short* buffer, int bufferSize)
  {
    for(int i=0; i<bufferSize; i++)
    {
      Console::WriteLine(*(buffer + i));
    }
  }
};





static void Main()
{
  MyClass obj = new MyClass();

  unsafe
  {
      int len = 10;
      ushort[] buff = new ushort[len];
      for (ushort i = 0; i < len; i++)
      {
          buff[i] = (ushort)(i * 10);
      }

      fixed (ushort* pBuff = buff)
      {
          obj.ProcessBuffer(pBuff, len);
      }
  }
}


你好

如果您在C#应用程序中启用了不安全的代码,则可以使用固定语句:
Hello

If you have unsafe code enabled in your C# application you can use the fixed statement:
static unsafe void SomeMethod(byte[] args)
{
    fixed (byte* ptr = args)
    {
        ushort* ptrUs = (ushort*)ptr;
        MyManagedLibrary.MyClass.FooBar(ptrUs, args.Length / 2);
    }
}



但是请记住,不安全"关键字表示不安全.没有更多的检查,您可以轻松获得访问冲突.但是,如果您知道自己在做什么,那没问题;)



But keep in mind that the "unsafe" keyword means unsafe. There are no more checks and you can easily get access violations. But if you know what you are doing its no problem ;)


这篇关于从C#将byte []传递到C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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