DLLImport c++带默认参数的函数

发布于 2024-09-25 09:36:49 字数 385 浏览 5 评论 0原文

我正在尝试将非托管代码 c++ dll 中的函数导入到我的 c# 应用程序中。 C++ 原型是

int somefunction (int param1, int *param2 = NULL);

How do I statements this in c# to take Advantage of the default nature of param2?下面的代码不起作用。 param2 用垃圾初始化。

DllImportAttribute("mydll.dll", EntryPoint = "somefunction")]
public static extern int somefunction(int param1);

I am trying to import a function from an unmanaged code c++ dll into my c# application. The c++ prototype is

int somefunction (int param1, int *param2 = NULL);

How do I declare this in c# to take advantage of the default nature of param2? The following code does not work. param2 gets initialized with garbage.

DllImportAttribute("mydll.dll", EntryPoint = "somefunction")]
public static extern int somefunction(int param1);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

音栖息无 2024-10-02 09:36:49

如果您使用 C# 4.0,那么 dtb 的答案是正确的方法。 C# 4.0 添加了可选参数支持,它们与 PInvoke 函数配合得很好。

在 C# 4.0 之前,无法利用可选参数。最接近的等效方法是定义一个转发到另一个函数的函数。

[DllImport("mydll.dll", EntryPoint = "somefunction")] 
static extern int somefunction(int param1, IntPtr param2);

static int somefunction(int param1) {
  someFunction(param1, IntPtr.Zero);
}

If you are using C# 4.0 then dtb`s answer is the right approach. C# 4.0 added optional parameter support and they work just as well with PInvoke functions.

Prior to C# 4.0 there is no way to take advantage of the optional parameter. The closest equivalent is to define one function that forwards into the other.

[DllImport("mydll.dll", EntryPoint = "somefunction")] 
static extern int somefunction(int param1, IntPtr param2);

static int somefunction(int param1) {
  someFunction(param1, IntPtr.Zero);
}
叹梦 2024-10-02 09:36:49

尝试

[DllImport("mydll.dll", EntryPoint = "somefunction")]
static unsafe extern int somefunction(int param1, int* param2 = null);

[DllImport("mydll.dll", EntryPoint = "somefunction")]
static extern int somefunction(int param1, IntPtr param2 = default(IntPtr));

Try

[DllImport("mydll.dll", EntryPoint = "somefunction")]
static unsafe extern int somefunction(int param1, int* param2 = null);

or

[DllImport("mydll.dll", EntryPoint = "somefunction")]
static extern int somefunction(int param1, IntPtr param2 = default(IntPtr));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文