当用作c /CLI中函数的参数(托管)时,相当于c /CLI中的c#类



我有一个c#文件如下:

//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
}

我刚刚在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 = %dn", x, y, result);
    return 0;
}

C项目无缝调用c++/CLI。

相关内容

  • 没有找到相关文章

最新更新