返回 int、API 时的 Pinvoke [英] Pinvoke upon return of int, API

查看:51
本文介绍了返回 int、API 时的 Pinvoke的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我目前遇到了从 C# windows 应用程序调用 Win32 DLL[Native] 的问题.


I am currently running into an issue of calling an Win32 DLL[Native] from a C# windows application.

我已经走了这么远.

C++ 源代码:

extern "C" __declspec(dllexport) int PlaceSound(__in DWORD frequence, __in DWORD duration)
{
    Beep(frequence, duration);
    return 0;
}

C# 源代码:

[DllImport("SampleLib.dll")]
    public extern static int PlaceSound(int Freq, int Dura);

 public form1 { InitializeComponements; PlaceSound(150, 500); }

在调试时,我收到了声音,但是,当库返回其整数值时,我似乎得到了一个 pinvoke.

Upon debugging, I recieve the sound, however, when the library returns its integer value I seem to get a pinvoke.

Pinvoke:
对 PInvoke 函数SoundTracer!SoundTracer.Form1::PlaceSound"的调用使堆栈不平衡.这可能是因为托管 PInvoke 签名与非托管目标签名不匹配.检查 PInvoke 签名的调用约定和参数是否与目标非托管签名匹配.

我做错了什么?

Pinvoke:
A call to PInvoke function 'SoundTracer!SoundTracer.Form1::PlaceSound' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

What am I doing wrong?

推荐答案

C++ 编译器的默认调用约定是 cdecl,但是 p/invoke 的默认调用约定是 stdcall.这种不匹配就是您看到的消息的原因.

The default calling convention of the C++ compiler is cdecl, but the default calling convention for p/invoke is stdcall. That mismatch is the reason for the message that you see.

另外,为了 100% 正确,DWORD 是一个无符号整数,应该与 uint 匹配.

Also, to be 100% correct, DWORD is an unsigned integer and should be matched with uint.

所以你需要像这样导入:

So you need to import it like this:

[DllImport("SampleLib.dll", CallingConvention=CallingConvention.Cdecl)]
public extern static int PlaceSound(uint Freq, uint Dura);

这篇关于返回 int、API 时的 Pinvoke的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆