简体   繁体   English

Pinvoke期间第二个值未传递到C ++函数

[英]Second value not getting passed to C++ function during pinvoke

I have a c++ function which I am calling from c# using pinInvoke. 我有一个使用pinInvoke从c#调用的c ++函数。 Following is my cpp method- 以下是我的cpp方法-

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

My function is exposed as - 我的功能暴露为-

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

Following is my c# code where I am calling the above method: 以下是我调用上述方法的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);
    }
}

Here the second value is getting passed as 0,so wrong result is coming. 在这里,第二个值被传递为0,因此将出现错误的结果。 Am I doing something wrong while passing the value? 传递值时我做错什么了吗?

What I have tried: 我尝试过的

I am relatively new to Pinvoke. 我对Pinvoke比较陌生。 So I tried debugging to see whether the value is not getting passed to c++ code or whether the c++ code is not returning proper values.I found that the value getting passed itself was wrong. 因此,我尝试调试以查看该值是否未传递给c ++代码或c ++代码是否未返回正确的值。我发现传递的值本身是错误的。

DWORD is a 32 but unsigned integer. DWORD是一个32但无符号的整数。 You are mapping that to a 64 bit type. 您正在将其映射到64位类型。 That is the problem. 那就是问题所在。 Your p/invoke should be: 您的p / invoke应为:

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

Note that I removed the needless EntryPoint and the erroneous SetLastError from the DllImport attribute. 请注意,我从DllImport属性中删除了不必要的EntryPoint和错误的SetLastError

I also wonder why you have selected DWORD . 我也想知道为什么您选择了DWORD Unless you are passing those values onto Win32 functions it would likely make more sense to use intrinsic types. 除非将这些值传递给Win32函数,否则使用固有类型可能更有意义。 Why not use int or unsigned int in your C++ code? 为什么不在C ++代码中使用intunsigned int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM