我有用C ++创建的DLL文件。它具有一个名为NewTestClass的类,并且是位于header.h中的TestClass的实例。
dllmain.cpp
#include "pch.h"
#include "header.h"
#include <winapifamily.h>
#include <string>
#define DllExport __declspec( dllexport )
BOOL APIENTRY DllMain(HMODULE /* hModule */, DWORD ul_reason_for_call, LPVOID /* lpReserved */)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
//class instance
DllExport TestClass NewTestClass;
void LoadBasicData() {
NewTestClass.name = "example";
NewTestClass.description = "example";
NewTestClass.icon = "../example.svg";
NewTestClass.diagram = "../1.png";
NewTestClass.category = "example";
};
void LoadDetails() {
NewTestClass.LoadXAML = "info.xaml";
}
int main() {
LoadBasicData();
LoadDetails();
}
我想通过将C ++ dll(上面的代码)加载到我的C#应用程序中来使用NewTestClass类中的数据。因此在我的C#应用程序中,我通过使用DLLImport调用dll
MainPage.xaml.cs
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
public sealed partial class MainPage : Frame
{
////////********
[DllImport("mydll.dll")]
public static extern class WebTemplate;
///////*********
public MainPage()
{
this.InitializeComponent();
}
}
}
所有星号所在的位置就是问题所在。它导致错误“属性'DllImport'在此声明类型上无效。仅在'方法'声明上有效”所以只能从dllImport读取函数和数据类型吗?有解决这个问题的方法吗?
确保您的C++
库为正确:
[DllImport("yourLib.dll", EntryPoint = "yourFunction")]
public static extern <return type> YourFuncName(String str, int integer);
示例:如果要YourFuncName
返回int
类型,则C++
也要在int
中返回C#
:
[DllImport("yourLib.dll", EntryPoint = "yourFunction")]
public static extern int YourFuncName(String str, int integer);
对应的数据类型:
C ++-> C#
String
-> string
(或您可以使用String
)
int
-> int