Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
I have googled a lot but of no help.

I have an audio buffer of type byte[] of known size in my C# appication.
C#
public int processAudioBuffer(Byte[] buffer, int bufferSize)
{
//need to call the C++/CLI function ProcessBuffer()
}

I have a C++/CLI dll which takes this buffer and pass it to the native code
VB
ProcessBuffer(unsigned short* buffer, int buffersize);

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!
Posted

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:

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


C#
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);
      }
  }
}
 
Share this answer
 
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 ;)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900