当前访客身份:游客 [ 登录 | 加入开源中国 ]

代码分享

当前位置:
代码分享 » C/C++  » 编程基础
margaritaville

exe->c dll->c# dll

margaritaville 发布于 2016年08月16日 9时, 0评/311阅
分享到: 
收藏 +0
0
ref: http://www.codeproject.com/Articles/16206/Call-C-code-from-C-and-read-an-array-of-struct-whi
标签: <无>

代码片段(6) [全屏查看所有代码]

1. [代码].cs文件     跳至 [1] [3] [4] [5] [6] [全屏预览]

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace csharpdll
{

    [StructLayout(LayoutKind.Sequential)]
    public struct MyStruct
    {
        [MarshalAs(UnmanagedType.BStr)]
        public string name;
        [MarshalAs(UnmanagedType.BStr)]
        public string surname;
        public int age;
    }


    public interface ITest
    {
        MyStruct[] GetData
        {
            get;
        }

        int csharptest(int a);
    }
    public class Test : ITest
    {

        MyStruct[] st = new MyStruct[2];
        public Test()
        {
            st[0].name = "abc";
            st[0].surname = "def";
            st[0].age = 10;

            st[1].name = "qwe";
            st[1].surname = "rty";
            st[1].age = 20;
        }

        public MyStruct[] GetData
        {
            get
            {
                return st;
            }

        }

        public int csharptest(int a)
        {
            Console.WriteLine("Here we go, now u win!!!!");
            return 0;
        }
    }
}

2. [图片] Capture.PNG    

3. [代码]命令行执行     跳至 [1] [3] [4] [5] [6] [全屏预览]

regasm MyInterOp.dll /tlb:MyInterOp.tlb

4. [代码].cpp文件     跳至 [1] [3] [4] [5] [6] [全屏预览]

/// MUST DO
#import "C:\Workspace\autotesting\dlltester\player\csharpdll\bin\Debug\csharpdll.tlb"


/// MUST DO
using namespace csharpdll;

extern "C" __declspec(dllexport) int __stdcall cdlltest(int a)
{
    ITest* pTest = NULL;

    HRESULT hr = CoCreateInstance(__uuidof(Test),NULL,CLSCTX_INPROC_SERVER,
        __uuidof(ITest),(void**)&pTest);

    pTest->csharptest(0);

    return 0;
}

5. [代码].def文件     跳至 [1] [3] [4] [5] [6] [全屏预览]

; cdll.def : Declares the module parameters for the DLL.

LIBRARY      "cdll"

EXPORTS
    ; Explicit exports can go here
    cdlltest

6. [代码]exe     跳至 [1] [3] [4] [5] [6] [全屏预览]

        HINSTANCE hmod = ::LoadLibrary("cdll.dll");
        if(hmod == NULL) {
            std::cout << "Failed to load library." << std::endl;
            return FALSE;
        }

        typedef int (__stdcall *pfnLoadPODlg)(int);
        pfnLoadPODlg pfn = (pfnLoadPODlg)::GetProcAddress(hmod, "cdlltest");
        int ret = pfn(0);

        ::FreeLibrary(hmod);


开源中国-程序员在线工具:Git代码托管 API文档大全(120+) JS在线编辑演示 二维码 更多»

开源从代码分享开始 分享代码
margaritaville的其它代码 全部(18)...