繁体   English   中英

C ++ CLI从非托管代码中调用托管代码

[英]C++ cli call managed code from unmanaged code

我正在尝试学习如何在CLI / C ++中编写混合代码。

clrHookLib.h

#pragma once
#pragma managed
using namespace System;
namespace clrHookLib {

    ref class MyClass
    {
        // TODO: Add your methods for this class here.
        public:
        static int sum(int a, int b);
    };

}

clrHookLib.cpp

#include "stdafx.h"
#include "clrHookLib.h"

int clrHookLib::MyClass::sum(int a, int b)
{
    return a + b;
}

main.cpp中

#include "clrHookLib.h"
#include "Stdafx.h"

#pragma unmanaged

BOOL WINAPI DllMain(
    _In_ HINSTANCE  hInstance,
    _In_ DWORD      Reason,
    _In_ LPVOID     Reserved)
{
    switch (Reason)
    {
        case DLL_PROCESS_ATTACH:
        {
            int b = clrHookLib::MyClass::sum(1, 2);
            std::string str = std::to_string(b);
            MessageBoxA(0, str.c_str, "result from managed code!!", MB_OK);
            break;
        }
    }
}

在编译Visual Studio时向我显示了一个错误:

Error   2   error C2653: 'clrHookLib' : is not a class or namespace name    C:\Users\*\Documents\Visual Studio 2013\Projects\clrHookLib\clrHookLib\Main.cpp 15  1   clrHookLib
Error   3   error C3861: 'sum': identifier not found    C:\Users\*\Documents\Visual Studio 2013\Projects\clrHookLib\clrHookLib\Main.cpp 15  1   clrHookLib
Error   4   error C3867: 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::c_str': function call missing argument list; use '&std::basic_string<char,std::char_traits<char>,std::allocator<char>>::c_str' to create a pointer to member C:\Users\*\Documents\Visual Studio 2013\Projects\clrHookLib\clrHookLib\Main.cpp 17  1   clrHookLib

问题是为什么编译器无法找到clrHookLib命名空间? 我在做什么错?

谢谢。

[添加]

我在Microsoft网站上找到了一些代码。 可能对某人有用:

// initializing_mixed_assemblies.cpp
// compile with: /clr /LD 
#pragma once
#include <stdio.h>
#include <windows.h>
struct __declspec(dllexport) A {
   A() {
      System::Console::WriteLine("Module ctor initializing based on global instance of class.\n");
   }

   void Test() {
      printf_s("Test called so linker does not throw away unused object.\n");
   }
};

#pragma unmanaged
// Global instance of object
A obj;

extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) {
   // Remove all managed code from here and put it in constructor of A.
   return true;
}

我认为,无可奉告

您曾经使用#pragma unmanaged

因此,您不能在那里使用任何托管代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM