首页 > 解决方案 > 如何将带有字符串的结构从 C++ 传递到 C#

问题描述

我有以下 C++ 代码

#ifdef EXPORT_DLL
#define CfgAPI __declspec(dllexport)
#else
#define CfgAPI
#endif


    struct WrkPaths
    {
    public:
        char *WrkDir;
        char *URL1;
        char *URL2;
        char *URL3;
    };

    CfgAPI int getURLFromDir(WrkPaths * pathCfg){

        pathCfg->WrkDir  = (char*)malloc( 5 * sizeof(char) );
        strcpy( pathCfg->WrkDir , "Test");
        return 0;
    }

对应的C#代码

using System;
using System.Runtime.InteropServices;
using System.Text;

// namespace declaration 
namespace HelloWorldApp {

    // Class declaration 
    class Geeks {

        [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        public struct WrkPaths {

            [MarshalAs (UnmanagedType.LPStr, SizeConst = 255)]
            public string WrkDir;
            [MarshalAs (UnmanagedType.LPStr, SizeConst = 255)]
            public string URL1;
            [MarshalAs (UnmanagedType.LPStr, SizeConst = 255)]
            public string URL2;
            [MarshalAs (UnmanagedType.LPStr, SizeConst = 255)]
            public string URL3;
        }

        [DllImport ("CfgAPI.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int getRepoURLFromDir (
            ref WrkPaths wPath
        );

        // Main Method 
        static void Main (string[] args) {

            // statement 
            // printing Hello World! 
            Console.WriteLine ("Hello World!");

            WrkPaths wPath         = new WrkPaths();        
            int a = getRepoURLFromDir(ref wPath);

            Console.WriteLine (wPath.WrkDir.ToString ());


            // To prevents the screen from  
            // running and closing quickly 

            Console.ReadKey ();

        }
    }
}

仅在屏幕上Hello world出现。如何将数据从 C/C++ DLL 传输到 C#?

标签: c#c++dll

解决方案


推荐阅读