0

我有 ac# 文件如下:

//MyHandler.cs
public **class MyHandler**
{
**Function1(IntPtr handle)**
{....}
Function2(MyImageHandler myImgHandler,int height,int width)
{....}
};

public **class MyImageHandler**
{
FunctionX(string imagePath,int height,int width)
{.....}
};

我使用包含头文件的 c++/CLI 包装器 dll 来包装它,如下所示:

//IWrapper
#pragma once
#include<windows.h>
#include <string>

#ifdef MANAGEDWRAPPER_EXPORTS
#define DLLAPI  __declspec(dllexport)
#else
#define DLLAPI  __declspec(dllimport)
#pragma comment(lib,"D:\\MY\\MYY1\\Wrapper\\Debug\\MyFinalLibrary.lib")
#endif

class IWrapper
{
public:
   virtual DLLAPI void Function1(HWND  handle)=0;
   **virtual __stdcall void Function2(MyImageHandler myImageHandler,int width,int height)=0;**
};

** MyImageHandler 是一个托管类。所以我通过 __stdcall 导出它。我这样做对吗?** 现在我有一个实现上述头文件的头文件,然后是一个 cpp 文件,如下所示:

#include "Wrapper.h"
#include "IWrapper.h"
#include<vcclr.h>
#include <windows.h>
Function1(HWND handle)
{....}
Function2(MyImageHandler myImgHandler,int height,int weight)
{
//Here I need to typecast the MyImageHandler type to a managed handle
}
4

1 回答 1

0

我刚刚在 Visual Studio 2005 上对此进行了测试,效果很好:

//Project: InteropTestCsLib, class1.cs
namespace InteropTestCsLib
{
    public class Class1
    {
        public int Add(int a, int b) { return a+b; }
    }
}

一个 C++/CLI 项目,其中包含对 C# 的程序集引用,并且项目链接选项“忽略导入库”已禁用(默认情况下已启用)

//Project: InteropTestCppCliLib, InteropTestCppCliLib.h
namespace InteropTestCppCliLib {

    public ref class MyWrapper abstract sealed
    {
    public:
        static int Add(int a, int b);
    };
}
//Project: InteropTestCppCliLib, InteropTestCppCliLib.cpp
namespace InteropTestCppCliLib {

int MyWrapper::Add(int a, int b)
{
    InteropTestCsLib::Class1^ obj = gcnew InteropTestCsLib::Class1();
    return obj->Add(a, b);
}

}

//Free function, neither in a namespace nor class, but still managed code
extern "C" int __stdcall MyWrapperAdd(int a, int b)
{
    return InteropTestCppCliLib::MyWrapper::Add(a, b);
}

和模块定义文件(.def):

LIBRARY "InteropTestCppCliLib"
EXPORTS
    MyWrapperAdd

最后是一个空的本机 Win32 C/C++ 项目,项目依赖于 C++/CLI DLL(或者简单地说,一个导入它生成的导入库的项目):

/*Project: InteropTestUnmanagedApp, main.c*/
#include <stdio.h>

__declspec(dllimport) int __stdcall MyWrapperAdd(int a, int b);

int main(void)
{
    int x = 10;
    int y = 32;
    int result = MyWrapperAdd(x, y);
    printf("%d + %d = %d\n", x, y, result);
    return 0;
}

C 项目无缝调用 C++/CLI 之一。

于 2013-05-22T12:53:48.087 回答