使用VB.NET中的参数调用C ++函数

时间:2016-12-20 16:41:49

标签: c++ vb.net dll parameters pinvoke

我有一个像这样的c ++ DLL:

#include "stdafx.h"
#include <string.h>
#include <iostream>
using namespace std;

BOOL booltest(string info1, string info2, DWORD dword1)
{
    if (dword1 == 5)
    {
        return FALSE;
    }
    if (!strcmp(info1.c_str(), "hello")) // check if info1 = "hello"
    {
        return FALSE; // if so return false
    }
    return TRUE; // if not return true
}

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

我在VB项目中的表单上有一个按钮控件,我想P / Invoke调用booltest函数。但我还需要传递参数!显然,托管和非托管之间的数据类型是不同的。!

任何人都有这个或有用的指针的工作解决方案?我一直尝试这样做一段时间......

谢谢(对不起英语)

编辑: 开始?

<DllImport("mydll.dll")>
Public Shared Function booltest(...?) As Boolean
End Function

2 个答案:

答案 0 :(得分:0)

免责声明:我还在学习VB.net,所以如果我错了就不要伤害我。

几周前我遇到了类似的问题。首先,确保为DLL添加对项目的引用。然后确保使用代码头部的“import”语句。之后,您应该能够正常调用函数。

答案 1 :(得分:-1)

自己解决了这个问题。

extern "C" {
    __declspec(dllexport) BOOL __stdcall booltest(BOOL test)
    {
        if (test)
        {
            return FALSE;
        }
        return TRUE;
    }
}

您可以在VB.NET中使用它,如下所示:

<DllImport("test.dll", CallingConvention:=CallingConvention.StdCall)>
Private Shared Function booltest(<MarshalAs(UnmanagedType.Bool)> ByVal test As Boolean) As Boolean
End Function

然后当你需要使用它时:

Dim b As Boolean = booltest(True)
If b = True Then
    MsgBox("true")
Else
    MsgBox("false")
End If

只需确保将DLL放入VB应用程序的启动路径中,以便它可以找到DLL,并将“test.dll”替换为您自己的DLL。您可以传递字符串,整数等。只需修改P / Invoke中的数据类型...

好的lukkk!