c++與 C# 交互總結

C#調用dll:

  const string path = @"x:\xx\xx.dll"; // 定义dll的位

  const CallingConvention calling_convention = CallingConvention.Cdecl;

 

一、字符串 

  例子1、 

    -》c++

      extern "C" __declspec(dllexport) char* getDevices(char* pid, char* vid)

      {

        string str = "test";
        return _strdup(str.c_str());
      }

        

    -》C#

      [DllImport(@path)]

      extern static IntPtr getDevice(string pid, string vid);

      

      IntPtr p = getDevice( pid, vid);
      string s = Marshal.PtrToStringAnsi(p);

   

  例子2、

    -》C++

      extern "C" __declspec(dllexport) char* strTocS(char *str )

      {
        const char* to = { "I xxx you" };
        int len = strlen(to)+1;
        str = new char[len];   // 必須申請堆內存,否則調用失敗
        strcpy_s(str, len, to);
        return str;
      }

     -》C# 

      [DllImport(@path, EntryPoint = "strTocS", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]

      extern static IntPtr strTocS();

      IntPtr str= strTocS();
      string s = Marshal.PtrToStringAnsi(str);
      Console.WriteLine(s);

 

二、結構體

  1)c++輸出,C#接入

    -》c++:      

      // 結構體 與 C# 交互
      typedef struct Stu
      {
        public:
        int Age;
        char Name[20];
      };
      extern "C" DLLExport void FindInfo(Stu & stu)
      {
        stu.Age = 10;
        strcpy_s(stu.Name, "徐滔");
      }

     -》C#     

      // 結構鋼
      [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
      public struct Stu
      {
        public int Age;
        [System.Runtime.InteropServices.MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
        public string Name;
      }
      [DllImport(@path, EntryPoint = "FindInfo", CallingConvention = CallingConvention.Cdecl,CharSet = CharSet.Unicode)]

      Stu stu = new Stu();

      FindInfo(ref stu);

      Console.WriteLine(stu.Name);


      

  2)c++接入,C#輸出

 

 

 

線上參考文檔:www.cnblogs.com/Chase/archive/2010/05/31/1748596.html

posted @ 2021-11-24 11:26  dcli  阅读(45)  评论(0)    收藏  举报