在C#中导入DLL [英] Importing a DLL in C#

查看:394
本文介绍了在C#中导入DLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用DllImport将dll导入我的C#项目中,如下所示:

I'm trying to import a dll to my C# project using DllImport as follows:

[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key,string val,string filePath);

此外,我添加了名称空间System.Runtime.InteropServices:

Also, I have added the namespace System.Runtime.InteropServices:

using System.Runtime.InteropServices;

不过,我遇到了一个错误:
名称 DllImport没有存在于当前上下文中。

Still, I'm getting an error: "The name 'DllImport' does not exist in the current context"

在类中可以导入dll的位置是否受到限制?

Is there a limitation on where in a class you can import a dll?

推荐答案

您的语句中可能还返回了错误的返回类型。尝试使用 bool

You've probably also got the wrong return type in your statement. Try with bool:

[DllImport("kernel32")]
private static extern bool WritePrivateProfileString(string section, string key,string val,string filePath);

参考文献: http://msdn.microsoft.com/zh-cn/library/ms725501(v = vs.85).aspx

编辑

DllImport必须放置在类的主体内。不在方法或构造函数内部。

DllImports have to be placed inside the body of your class. Not inside methods or the constructor.

public class Class1
{
     //DllImport goes here:
     [DllImport("kernel32")]
     private static extern ...

     public Class1()
     {
          ...
     }

     /* snip */
}

这篇关于在C#中导入DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆