none
C#如何调用C++编译的dll中的函数 RRS feed

Answers

  • 假设C++ 写的DLL 的导出函数声明:

    LPCTSTR GetString(int a);
    GetString 函数所在的动态库名称为a.dll

    1) 将动态库放到PATH指定的路径或者当前路径下
    2) 在C# 代码文件中加入下列内容:
    using System.Runtime;
    using System.Runtime.InteropServices;

    在类声明中加入一个函数声明:
    [DllImport("a.dll", EntryPoint = "GetString", CharSet = "Auto")]
    private static extern string GetString(int a);

    3) 在C# 代码中适当的地方调用GetString函数

    也可参考:
    http://msdn.microsoft.com/en-us/magazine/cc164123.aspx
    • Marked as answer by 冰块。oO Friday, January 8, 2010 4:56 PM
    Friday, January 8, 2010 1:15 PM

All replies

  • 假设C++ 写的DLL 的导出函数声明:

    LPCTSTR GetString(int a);
    GetString 函数所在的动态库名称为a.dll

    1) 将动态库放到PATH指定的路径或者当前路径下
    2) 在C# 代码文件中加入下列内容:
    using System.Runtime;
    using System.Runtime.InteropServices;

    在类声明中加入一个函数声明:
    [DllImport("a.dll", EntryPoint = "GetString", CharSet = "Auto")]
    private static extern string GetString(int a);

    3) 在C# 代码中适当的地方调用GetString函数

    也可参考:
    http://msdn.microsoft.com/en-us/magazine/cc164123.aspx
    • Marked as answer by 冰块。oO Friday, January 8, 2010 4:56 PM
    Friday, January 8, 2010 1:15 PM
  • 你好!
         1,在C++中通过extern来暴露这个函数!
         2,在C#中这样声明这个函数:
              [DllImport("xxx.dll")]
              public static extern string GetString(....);
         3,然后在C#中直接调用GetString就可以了!
    周雪峰
    Friday, January 8, 2010 2:22 PM
    Moderator
  • 你好!
         1,在C++中通过extern来暴露这个函数!
         2,在C#中这样声明这个函数:
              [DllImport("xxx.dll")]
              public static extern string GetString(....);
         3,然后在C#中直接调用GetString就可以了!
    周雪峰

    Update 一下版主:

    1) extern "C" 是用来定义导出函数命名规则的。http://dev.csdn.net/article/66/66384.shtm
    2) 真正起到导出函数声明的是: __declspec(dllexport)

    Friday, January 8, 2010 11:54 PM
  • Michael Lee:
    这样写GetString是有问题的,因为返回的地址的内存所有权不明确。建议返回BSTR或者接受一个输入缓冲区。


    The following is signature, not part of post
    Please mark the post answered your question as the answer, and mark other helpful posts as helpful.
    Visual C++ MVP
    Sunday, January 24, 2010 12:12 AM
    Moderator
  • 路过在dllimport中好像还要添加CallingConvention=CallingConvention.Cdecl


    Tuesday, October 9, 2018 6:24 AM