我很困惑...我是一名 VB.net 程序员,我需要创建一个带有接收器的接口(interface)。向接收器发送数据没问题,我可以对频率、带宽和类似的东西进行编程……我不得不使用 C++ 与接收器通信。所以我决定试一试,用 C++ 创建一个 dll,然后在 VB.net 中制作 GUI。但是,当我想向接收者询问信息时,我卡住了......
我的 C++ 代码是这样的
char __stdcall Q_BW(){
MyPR100::sendSCPI(TCPsock, "SENS:BAND?\n");
char pRxBuf[256];
int len = recv(TCPsock, pRxBuf, sizeof(pRxBuf), 0);
if (len < 0) len = 0; pRxBuf[len] = '\0';
puts(pRxBuf);
return pRxBuf;
}
所以基本上,向接收器发送命令,并将结果放入缓冲区...现在需要将此缓冲区返回给 VB.net,这就是我失败的地方... 编译的时候报错
无法从“char[256]”转换为“char”
我可以看到我做错了什么,但显然我无法找到解决方案...dll 可以很好地向接收器发送数据,因此该部分可以正常工作... 完整地说,这是 VB.net 代码...
Private Declare Function Q_BW Lib "PR100Dll.dll" () As String
Dim Res As String = ""
Res = Q_BW()
MsgBox(Res, MsgBoxStyle.Information)
我知道这可能是一个菜鸟问题,但我真的被困在这里......因为我在 C++ 方面不是那么好(这是一个 understatement),而且英语不是我的母语,我会很高兴如果我得到了一个不那么困难的答案,我可以从中学到......哦,请注意我已经用谷歌搜索了 2 周了,我真的到了最后......
提前致谢...
最佳答案
我给你写了一个例子:
1.TestDll.cpp(dll中的函数)
#include "stdafx.h"
char* __stdcall ReadString()
{
return "ABCDEFG";
}
2.TestDll.def(导出ReadString函数)
LIBRARY TestDll
EXPORTS
ReadString
3.TestCS(CSharp演示)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace TestCS
{
class Program
{
[DllImport("TestDll.dll", CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr ReadString();
static void Main(string[] args)
{
IntPtr t = ReadString();
String result = Marshal.PtrToStringAnsi(t);
}
}
}
4.TestVB(VB演示)
Imports System.Runtime.InteropServices
Module Module1
Private Declare Function ReadString Lib "TestDll.dll" () As IntPtr
Sub Main()
Dim t As IntPtr
Dim result As String
t = ReadString
result = Marshal.PtrToStringAnsi(t)
End Sub
End Module
dll工程和CS工程、VB工程应该设置相同的charset。
关于c++ - C++ 2013 中的 Dll 需要将字符串返回给 VB.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39273384/