开发者

Importing a DLL in C#

开发者 https://www.devze.com 2023-03-21 08:09 出处:网络
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 fi

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);

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

using System.Runtime.InteropServices;

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

Is there a limitation on where in a class you can import 开发者_如何学编程a dll?


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);

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

EDIT:

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 */
}


In your solution explorer, right-click references, select Add Reference, and add the System.Runtime.InteropServices to your project.

You can't do 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.

i.e.:

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

code for Kenler32.dll inport

MSDN whit explanation

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号