我想使用kernel32.dll并且需要为此创建我自己的dll我创建了DllImp.cs代码,并希望在另一个文件中使用这些方法,例如pipe.cs,但是我收到的错误如
CreateNamedPipe is a method but is used like a type.
PipeName is a field but is used like a type
PIPE_ACCESS_DUPLEX is a field but is used like a type
PIPE_TYPE_MESSAGE is a field but is used like a type
我的代码是:
//DllImp.cs code
using System;
using System.Text;
using System.Security;
using System.Runtime.InteropServices;
namespace MessageManagerServer {
[SuppressUnmanagedCodeSecurity]
public sealed class DllImports {
[DllImport("kernel32.dll")]
public static extern IntPtr CreateNamedPipe(
String lpName, // pipe name
uint dwOpenMode, // pipe open mode
uint dwPipeMode, // pipe-specific modes
uint nMaxInstances, // maximum number of instances
uint nOutBufferSize, // output buffer size
uint nInBufferSize, // input buffer size
uint nDefaultTimeOut, // time-out interval
IntPtr pipeSecurityDescriptor); // SD
public const uint PIPE_ACCESS_DUPLEX = 0x00000003;
//public const uint PIPE_TYPE_BYTE = 0x00000000;
public const uint PIPE_TYPE_MESSAGE = 0x00000004;
//public const uint PIPE_READMODE_BYTE = 0x00000000;
public const uint PIPE_READMODE_MESSAGE = 0x00000002;
public const uint PIPE_WAIT = 0x00000000;
public const uint NMPWAIT_WAIT_FOREVER = 0xffffffff;
public const uint NMPWAIT_USE_DEFAULT_WAIT = 0x00000000;
public const int INVALID_HANDLE_VALUE = -1;
public const uint ERROR_IO_PENDING = 997;
public const uint PIPE_UNLIMITED_INSTANCES = 255;
public DllImp() {
}
}
这是pipe.cs代码
using System;
using System.Text;
using System.Security;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Collections;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Xml;
using System.Windows.Forms;
using System.Diagnostics;
namespace ClassLibrary1
{
public class Pipe
{
private string PipeName = "\\\\.\\pipe\\Honeywell";
public IntPtr Handle;
Handle = DllImp.CreateNamedPipe(PipeName,DllImp.PIPE_ACCESS_DUPLEX,
DllImp.PIPE_TYPE_MESSAGE |
DllImp.PIPE_READMODE_MESSAGE |
DllImp.PIPE_WAIT,
1,
0,
0,
1000,
IntPtr.Zero);
}
}
答案 0 :(得分:1)
你不能像这样初始化Handle
字段,你在初始化期间尝试访问实例字段:
public IntPtr Handle;
Handle = ...
这是不允许的,因为您可能在初始化之前访问该字段。
尝试一次性完成所有操作:
public IntPtr Handle = DllImp.CreateNamedPipe(PipeName,DllImp.PIPE_ACCESS_DUPLEX,
DllImp.PIPE_TYPE_MESSAGE |
DllImp.PIPE_READMODE_MESSAGE |
DllImp.PIPE_WAIT,
1,
0,
0,
1000,
IntPtr.Zero);
您也可以将初始化移动到类构造函数中,就像在Marcs回答中一样,这是更清洁的IMO。
public Pipe()
{
Handle = ....
}
答案 1 :(得分:0)
嗯,我:
DllImp
更改为DllImports
(因为这就是该类的名称)Handle =
代码移动到构造函数中(也可能使用了字段初始化程序,但这似乎保留了代码的意图)它编译得很好。
public Pipe()
{
Handle = DllImports.CreateNamedPipe(PipeName,
DllImports.PIPE_ACCESS_DUPLEX,
DllImports.PIPE_TYPE_MESSAGE |
DllImports.PIPE_READMODE_MESSAGE |
DllImports.PIPE_WAIT,
1,
0,
0,
1000,
IntPtr.Zero);
}
(也将DllImports
中的构造函数重命名为DllImports
)