在 C# 代码中导入 DLL 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15895112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:19:27  来源:igfitidea点击:

Importing DLL functions in c# code

c#c++cdllimportextern

提问by Amit Agrawal

I have a DLL, whose functions i want to use in my c# code Here are the functions of that DLL :

我有一个 DLL,我想在我的 c# 代码中使用它的函数 以下是该 DLL 的函数:

extern "C"
{
  __declspec(dllimport)
  const char* __stdcall ZAJsonRequestA(const char *szReq);

  __declspec(dllimport)
  const wchar_t* __stdcall ZAJsonRequestW(const wchar_t *szReq);

  __declspec(dllimport)
  const BSTR __stdcall ZAJsonRequestBSTR(BSTR sReq);
}

Can anyone tell me how to use it in c# project, as this dll seems to be in other language ?

谁能告诉我如何在 c# 项目中使用它,因为这个 dll 似乎是其他语言的?

回答by Spook

Use DllImportand MarshalAsattributes.

使用DllImportMarshalAs属性。

回答by Patrick D'Souza

Please have a look at the following articleon Code Project for an in depth explanation

请查看以下关于 Code Project 的文章以获得更深入的解释

A small sample from the linked article is as shown below

链接文章中的一个小样本如下所示

To call a function, say methodName

要调用函数,请说methodName

int __declspec(dllexport) methodName(int b)
{
      return b;
}

Include the class library (MethodNameLibrary.dll) containing the above method as shown below in c#

在 c# 中包含包含上述方法的类库 (MethodNameLibrary.dll),如下所示

class Program
{
   [DllImport(@"c:\MethodNameLibrary.dll")]
   private static extern int methodName(int b);
   static void Main(string[] args)
   {
       Console.WriteLine(methodName(3));
   }
}