Wrapping C++ CLI Class For C#

Wrapping C++ CLI Class For C#

本文关键字:For Class CLI C++ Wrapping      更新时间:2023-10-16

我正在尝试从C#调用一些Windows基本函数,特别是这个。从我也想学习C++/CLI 语言的那一刻起,我就写下了这段代码:


#pragma once
#include <string>
#include <Windows.h>
using namespace System;
namespace InformazioniSchermo {
    public class Native_InformazioniDaSistema
    {
    public:
        int m_nAltezzaPannello;
        int m_nLarghezzaPannello;
        Native_InformazioniDaSistema(void)
        {
            DISPLAY_DEVICE dd;
            DWORD dev = 0;
            dd.cb = sizeof(dd);
            EnumDisplayDevices(0, dev, &dd, 0);
            m_nAltezzaPannello = 100;
            m_nLarghezzaPannello = 100;
        }
    };
    public ref class InformazioniDaSistema
    {
    public:
        InformazioniDaSistema();
        ~InformazioniDaSistema();
    public:
        int m_nHeight;
        int m_nWidth;
    };
    InformazioniDaSistema::InformazioniDaSistema()
    {
        Native_InformazioniDaSistema foo;
        m_nHeight = foo.m_nAltezzaPannello;
        m_nWidth = foo.m_nLarghezzaPannello;
    }
    InformazioniDaSistema::~InformazioniDaSistema()
    {
    }
}

但是当我编译时,我收到此错误:

Error   3   error LNK2028: at unresolved token (0A0003B4) "extern "C" int __stdcall EnumDisplayDevicesW(wchar_t const *,unsigned long,struct _DISPLAY_DEVICEW *,unsigned long)" (?EnumDisplayDevicesW@@$$J216YGHPB_WKPAU_DISPLAY_DEVICEW@@K@Z) referencing in function "public: __thiscall InformazioniSchermo::Native_InformazioniDaSistema::Native_InformazioniDaSistema(void)" (??0Native_InformazioniDaSistema@InformazioniSchermo@@$$FQAE@XZ)  c:Usersmassimilianodocumentsvisual studio 2013ProjectsInformazioniSchermoInformazioniSchermoInformazioniSchermo.obj InformazioniSchermo

我哪里做错了?

您需要针对user32.libEnumDisplayDevices函数的库,如您将在链接到的 MSDN 页面中看到的那样)进行链接。

您可以通过转到项目属性->Linker->Input 并将user32.lib添加到"其他依赖项"列表中来执行此操作。

我注意到C++/CLI 的默认 Visual Studio 项目设置默认不包括常见的 Windows API 库(常规C++项目在新项目中的项目库依赖项中添加了 kernel32.libuser32.libshell32.lib 和其他库),因此如果您使用这些库,则必须自己添加这些库。

 error LNK2028: ... (?EnumDisplayDevicesW@@$$J216YGHPB_WKPAU_DISPLAY_DEVICEW@@K@Z) ...

这就是链接器要查找的名称。 那不是它的名字,它是一个 C 函数,没有C++名称重整。 非常不清楚你是怎么做到的,尤其是因为你混淆了你的 #includes。 但唯一合理的猜测是您自己声明了此函数,而不是在 SDK 标头中使用其声明。

永远不要那样做。 而是使用:

  #include <Windows.h>
  #pragma comment(lib, "user32.lib")

#pragma 有帮助,因此您不会忘记链接到user32