【问题标题】:Using a Pointer as a Buffer in C# for an External Function在 C# 中将指针用作外部函数的缓冲区
【发布时间】:2016-10-06 23:23:13
【问题描述】:

我正在将外部 C++ 函数从 dylib 导入 Unity C#。有问题的函数如下所示:

[DllImport ("librtcmix_embedded")]
unsafe private static extern int RTcmix_runAudio(void* k, void *outAudioBuffer, int nframes);

它接收一个指针并将音频信息写入固定大小缓冲区中的该指针。我有一个来自 Unity 的 C# 函数,它应该将此信息放入缓冲区:

 void OnAudioFilterRead(float[] data, int channels)

理想情况下,在 OnAudioFilterRead 的主体中,我将能够声明一个固定大小的指针 int*(2048,Unity 的音频使用的样本数)并将其输入 RTcmix_runaudio 的 outAudioBuffer 参数,然后从中复制信息指向浮点数据数组的指针。

    void OnAudioFilterRead(float[] data, int channels)
{
    int *buffer = new int*(2048); //this line is not proper c#, how do I do this?
    RTcmix_runAudio (null, buffer, 2048);
    for(int i = 0; i<2048; i++){
        data[i] = (float) buffer[i];
    }
}

但是,我不知道如何在 C# 中获得大小为 2048 的正常工作指针。有什么帮助吗?我所有输入数组或使用固定结构的尝试都导致程序崩溃。

【问题讨论】:

    标签: c# c++ pointers unity3d buffer


    【解决方案1】:

    通过使用Marshal.AllocHGlobal,您可以分配一个由 IntPtr 指向的 8192 字节(2048 x 32 位样本)的非托管缓冲区,并将其传递给 DLL。然后使用Marshal.Copy 将非托管缓冲区内容复制到托管 int[] 中。然后我使用 Linq 将缓冲区“转换”为 float[]。使用 FreeHGlobal 释放非托管缓冲区。

    我假设缓冲区由 4 个字节的整数组成。如果它实际上包含 float,则将目标类型更改为 float[],C# 将调用正确的 Marshal.Copy。

    using System;
    using System.Linq;
    using System.Runtime.InteropServices;
    
    public static class DLL
    {
        [DllImport("librtcmix_embedded")]
        public static extern int RTcmix_runAudio(IntPtr k, IntPtr outAudioBuffer, int nframes);
    }
    
    public class MyTest
    {
        void OnAudioFilterRead(out float[] data, int channels)
            {
                int[] destination = new int[channels];
                IntPtr buffer = Marshal.AllocHGlobal(4*channels);
    
                DLL.RTcmix_runAudio((IntPtr)0, buffer, channels);            
    
                Marshal.Copy(buffer, destination, 0, channels);
    
                Marshal.FreeHGlobal(buffer);
    
                data = destination.Select(item => (float)item).ToArray();
    
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多