c - 如何在 VBA(Excel Visual Basic)中从 DLL 接收 "char *d"?

标签 c vba excel dll

现在我正在尝试获取一个 char 字符串作为下面的 c 函数。
这是DLL的C函数,

char _stdcall *fmt_hex(long long num, int nbits, char *d)
{
    sprintf(d, "0x%0*llX", (nbits - 1) / 4 + 1, num);
    return (d);
}
下面是 Excel VBA 函数。
Option Explicit

Private Declare PtrSafe Function pll_dll Lib "F:\work\pll_dll\x64\Debug\pll_dll.dll" (ByVal num As LongLong, ByVal nbits As Integer, ByRef d As String)

Dim d As String

Sub useSquareInVBA()
    
    Cells(4, 4).Text = pll_dll(3, 4, d)

End Sub
但是当我运行这段代码时,我的程序停止了。
你能告诉我我应该做些什么来解决这个问题吗?
更新2
当我使用此代码运行时
“C”
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double _stdcall pll_dll(double* datain0, double* datain1, double* dataout0, double* dataout1,  char * str)
{
    dataout0[0] = datain0[0] + 10;
    dataout1[0] = datain1[0] + 10;
    
    str ="c";
    
    return 0;
}
“VBA”
Option Explicit

Private Declare PtrSafe Function pll_dll Lib "F:\work\pll_dll\x64\Debug\pll_dll.dll" _
(ByRef x_in As Double, ByRef y_in As Double, ByRef x_out As Double, ByRef y_out As Double, ByRef str As String) As Double

Dim Error As Integer

Dim d1 As Double
Dim d2 As Double
Dim d3 As Double
Dim d4 As Double
Dim sometext As String


Function pll_dll_excel(data1 As Double, data2 As Double, data3 As Double, data4 As Double, text As String) As Double

pll_dll_excel = pll_dll(data1, data2, data3, data4, text)
    
End Function

Sub useSquareInVBA()
    MsgBox pll_dll_excel(3, 4, d1, d2, sometext)
    Cells(5, 5).Value = d1
    Cells(6, 6).Value = d2
    Cells(7, 7).Value = sometext
End Sub
不,程序停止,但 sometext 始终为空 ""值。
你能帮我吗?
更新3
我已经从这里查看了这篇文章。
How to return a string of unknown size from DLL to Visual Basic
当我阅读这篇文章时,我意识到这不是“C”。
我如何制作为“C”?

最佳答案

我遇到了类似的问题,这篇文章是最相关的搜索结果。
我没有直接解决问题(归功于 GSerg 以提出正确的方法),而是发布了我如何实现接收作为引用传递的 char 数组的通用版本:
C 函数(共享库):

int func(int a, double b, char *result) {
    ...
    result[0] = 'A';
    result[1] = 'B';
    result[2] = '\0';
    return EXIT_SUCCESS;
}
VBA:
Option Explicit

' Import DLL function
Private Declare PtrSafe Function func Lib "C:\path\to\c-shared-library.dll" _
    (ByVal a As Integer, ByVal b As Double, ByVal result As String) As Integer

' Functions for use by Excel - DLL functions cannot be directly used
Function getResult(ByVal a As Integer, ByVal b As Double) As String
    Dim status As Integer
    Dim result As String
    result = Space$(2)
    status = func(a, b, result)
    If status = 0 Then getResult = result Else Err.Raise 1000, "Error", "Failed to get result"
End Function
在我的情况下,结果总是一个两个字符数组,但我认为可以相应地修改上述方法。

关于c - 如何在 VBA(Excel Visual Basic)中从 DLL 接收 "char *d"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42756645/

相关文章:

c++ - SPOJ SUMFOUR.....TLE 在测试用例 9 上

c++ - 通过函数指针从外部文件调用静态函数的坏习惯?

vba - 使用 VBA 验证 Excel 下拉列表

excel - 在 INDEX 和 RANDBETWEEN 中添加范围

excel - 获取单元格在指定范围内的行号

c - 从文件中读取并将输出打印到文件

c - 如果线程崩溃,线程和进程哪个更好?

vba - 查找时的错误代码为 91

sql - MS Access - 如何增加不同表中的数字?

excel - 将主工作表中的过滤器应用于多个工作表