【问题标题】:Passing char pointer from C# to c++ function将 char 指针从 C# 传递给 C++ 函数
【发布时间】:2011-05-22 02:38:21
【问题描述】:

我被困在 c# 实现方面,因为我对它很陌生。问题是,我想从 c# 代码传递一个“指针”(具有内存),以便我的 c++ 应用程序可以将 pchListSoftwares 缓冲区复制到 pchInstalledSoftwares。我无法弄清楚如何从 c# 端传递指针。

原生c++代码(MyNativeC++DLL.dll)

void GetInstalledSoftwares(char* pchInstalledSoftwares){
    char* pchListSoftwares = NULL; 
    .....
    .....
    pchListSoftwares = (char*) malloc(255);

    /* code to fill pchListSoftwares buffer*/

    memcpy(pchInstalledSoftwares, pchListSoftwares, 255);

    free(pchListSoftwares );

}

传递简单的“字符串”不起作用...

C#实现

[DllImport("MyNativeC++DLL.dll")]
private static extern int GetInstalledSoftwares(string pchInstalledSoftwares);


static void Main(string[] args)
{
.........
.........
        string b = "";
        GetInstalledSoftwares(0, b);
        MessageBox.Show(b.ToString());
}

非常感谢任何形式的帮助...

【问题讨论】:

    标签: c# c++ unmanaged managed


    【解决方案1】:

    尝试使用 StringBuilder

    [DllImport("MyNativeC++DLL.dll")]
    private static extern int GetInstalledSoftwares(StringBuilder pchInstalledSoftwares);
    
    
    static void Main(string[] args)
    {
    .........
    .........
            StringBuilder b = new StringBuilder(255);
            GetInstalledSoftwares(0, b);
            MessageBox.Show(b.ToString());
    }
    

    【讨论】:

      【解决方案2】:

      我的错误...在调用 GetInstalledSoftwares(0, b); 时删除 0。

      【讨论】:

        【解决方案3】:

        尝试将原型线改为:

        private static extern int GetInstalledSoftwares(ref string pchInstalledSoftwares); 
        

        (通过引用发送字符串)。

        【讨论】:

          猜你喜欢
          • 2021-12-02
          • 2018-08-11
          • 2012-07-28
          • 1970-01-01
          • 2021-09-07
          • 2015-02-03
          • 2011-04-17
          • 2017-08-30
          • 1970-01-01
          相关资源
          最近更新 更多