调用API的时候,如果结构要设置为NULL,那在C#中应该如何实现啊?(200分)

  • 主题发起人 honestman
  • 开始时间
H

honestman

Unregistered / Unconfirmed
GUEST, unregistred user!
调用API的时候,如果结构要设置为NULL,那在C#中应该如何实现啊?
例如:
HANDLE CreateEvent(
LPSECURITY_ATTRIBUTES lpEventAttributes,
BOOL bManualReset,
BOOL bInitialState,
LPTSTR lpName
);

Parameters
lpEventAttributes
Ignored. Must be NULL.
那在C#中应该如何设置啊?
 
?不就是参数lpEventAttributes设为null吗?
 
如果是这么简单,我就不用在这里问啦!
 
由于C#里面的null,和C++里面的NULL,不等同。
这个问题我想应该有两种办法解决:
1。用Visual C++写一个wrapper dll, C#调用就省了NULL这个参数,通过C++来完成;
2。有书说可以用 int 来替代,原文如下:
if the code you create will never pass the structure to Windows (in other words, the structure is always passed as a NULL value), you can normally use an int as a substitute for the structure.
第二种没有试过,不知道是用int 还是 int 指针?
 
这样子用
class Class1
{
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public uint nLength;
public IntPtr lpSecurityDescriptor;

bool bInheritHandle;

}
[DllImport("Kernel32.dll")]
static extern int CreateEvent(ref SECURITY_ATTRIBUTES lpEventAttributes,
bool bManualReset,
bool bInitialState,
[MarshalAs(UnmanagedType.LPTStr)] string lpName);
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
SECURITY_ATTRIBUTES lpEventAttributes = new SECURITY_ATTRIBUTES();;

int i = CreateEvent(ref lpEventAttributes, false, false, "test");
Console.WriteLine(i);
}
 
我想应该caidaoli的方法的可行的吧?
不过,我已经把那结构改定义为类,这样就可以用NULL了。
问题自己解决了,大家都有分。
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
D
回复
0
查看
1K
DelphiTeacher的专栏
D
顶部