简体   繁体   English

在 C# 中导入 DLL

[英]Importing a DLL in C#

I'm trying to import a dll to my C# project using DllImport as follows:我正在尝试使用 DllImport 将 dll 导入我的 C# 项目,如下所示:

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

Also, I have added the namespace System.Runtime.InteropServices:另外,我添加了命名空间 System.Runtime.InteropServices:

using System.Runtime.InteropServices;

Still, I'm getting an error: "The name 'DllImport' does not exist in the current context"不过,我收到一个错误:“当前上下文中不存在名称‘DllImport’”

Is there a limitation on where in a class you can import a dll?在 class 中可以导入 dll 的位置是否有限制?

You've probably also got the wrong return type in your statement.您的语句中可能还有错误的返回类型。 Try with bool :尝试使用bool

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

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

EDIT :编辑

DllImports have to be placed inside the body of your class. DllImports 必须放在 class 的主体内。 Not inside methods or the constructor.不在方法或构造函数内部。

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

     public Class1()
     {
          ...
     }

     /* snip */
}

In your solution explorer, right-click references, select Add Reference, and add the System.Runtime.InteropServices to your project.在您的解决方案资源管理器中,右键单击引用 select 添加引用,然后将 System.Runtime.InteropServices 添加到您的项目中。

You can't do using <assembly>;你不能using <assembly>; if it's not also referenced in your project.如果您的项目中也没有引用它。

EDIT编辑

Actually, just saw your comment on your question.实际上,刚刚看到您对您的问题的评论。 I think (haven't done Interop in a while) that it has to be outside a function, in the body of the class.我认为(有一段时间没有进行互操作了)它必须在 function 之外,在 class 的主体中。

ie: IE:

public class MyClass
{

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

    public MyClass()
    {
    }

    public void foo()
    {
    }

    // etc, etc
}

Try Adding these parameters尝试添加这些参数

[DllImport("kernel32",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]

usually when importing win dll you use unsafe code sow be sure to check the project settings here are two simple tutorial that shows the code通常在导入win dll时你使用不安全的代码所以一定要检查项目设置这里有两个显示代码的简单教程

code for Kenler32.dll inport Kenler32.dll 进口代码

MSDN whit explanation MSDN白衣解释

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

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