使用来自VB.NET的参数调用C 函数

Call C++ function with parameters from VB.NET

本文关键字:参数 调用 函数 NET VB      更新时间:2023-10-16

我得到了一个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/instoke调用Booltest函数。但是我还需要传递参数!显然,托管和未管理之间的数据类型是不同的。!

有人对此指示有工作解决方案吗?我一直在tryna做了一段时间...

谢谢(对英语的抱歉)

编辑:开始?

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

免责声明:我仍在学习vb.net,所以如果我错了,请不要伤害我。

我几周前遇到了类似的问题。首先,请确保您为DLL的项目添加参考。然后确保您在代码头上使用"导入"语句。之后,您应该能够正常调用功能。

我自己解决了问题。

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,然后用自己的dll替换" test.dll"即可。您可以传递字符串,整数等。

好的lukkk!