在pinvoke期间没有传递给C ++函数的第二个值

时间:2017-05-25 09:02:40

标签: c# c++ .net dll pinvoke

我有一个c ++函数,我使用pinInvoke从c#调用。以下是我的cpp方法 -

int test(DWORD verb,DWORD verb2 )
{
    return verb2 *100;
}

我的功能公开为 -

extern "C" {
    __declspec(dllexport) int test(DWORD verb, DWORD verb2);
}

以下是我的c#代码,我在调用上述方法:

public class API
{
    [DllImport("mydll.dll", EntryPoint = "test", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
    [return: MarshalAs(UnmanagedType.U4)]
    public static extern uint test(
        [MarshalAs(UnmanagedType.U8)]ulong verb,
        [MarshalAs(UnmanagedType.U8)]ulong verb2);

    static void Main(string[] args)
    {
        uint x = DPAPI.test(26,10);
        Console.Write("result is-"+x);
    }
}

这里第二个值被传递为0,因此错误的结果即将到来。传递价值时我做错了吗?

我尝试过:

我对Pinvoke相对较新。所以我尝试调试以查看值是否未传递给c ++代码或者c ++代码是否没有返回正确的值。我发现传递给它的值本身是错误的。

1 个答案:

答案 0 :(得分:2)

DWORD是32但无符号整数。您将其映射到64位类型。那就是问题所在。你的p / invoke应该是:

[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int test(uint verb, uint verb2);

请注意,我从EntryPoint属性中移除了不必要的SetLastError和错误的DllImport

我也想知道为什么你选择了DWORD。除非您将这些值传递给Win32函数,否则使用内部类型可能更有意义。为什么不在C ++代码中使用intunsigned int