如何通过DLL函数的参数将变量返回到Excel
How to return a variable through an argument of a DLL function to Excel?
我有一个C++函数,通过使用VC2013:构建的DLL在Excel 2013中使用
double my_function(double input) {
//do something
return input*input;
}
在Excel VBA中,我包含这样的函数:
Declare Function my_function Lib "DLL_with_my_function.dll" (ByVal input As Double) As Double
到目前为止,这一切都很好,但是,现在,我希望能够通过第二个参数返回第二条信息,比如错误代码。理想情况下,这个错误代码可以输出到Excel中的一个单元格,或者至少可以通过debug.print输出到控制台。这是我徒劳的尝试:
double my_function(double input, long *error_code) {
*error_code = 5;
return input*input;
}
#in Excel:
Declare Function my_function Lib "DLL_with_my_function.dll" (ByVal input As Double, ByRef error_code as long) As Double
当我从工作表中调用函数并将单元格指示为第二个参数时,Excel会崩溃。正确、优雅的方法是什么?
您不能将exel单元格作为长数字赋予c\c++,因为它不会自动转换
你可以这样做:
double my_function(double input, long *error_code) {
*error_code = 5;
return input*input;
}
//unless you don't want to build the long from bytes, you can use function to do so.
long get_error_code(long* error_code ){
return *error_code;
}
在Excel中也声明新函数:
Declare Function my_function Lib "DLL_with_my_function.dll" (ByVal input As Double, ByVal error_code as long) As Double
Declare Function get_error_code Lib "DLL_with_my_function.dll" (ByVal error_code as long) As Long
#now in the function you should allocate memory to the error code:
Dim hMem As Long, pMem As Long
#hMem is handle to memory not a pointer
hMem = GlobalAlloc(GMEM_MOVEABLE Or GMEM_ZEROINIT, 10)
#pMem is your pointer
pMem = GlobalLock(hMem)
#now you can call to my_function with the pointer:
retval = my_function(input, pMem)
#in VB there is auto cast so this will work:
YourCell = get_error_code(pMem)
# Unlock memory make the pointer useless
x = GlobalUnlock(hMem)
# Free the memory
x = GlobalFree(hMem)
相关文章:
- 你能重载对象变量名本身返回的内容吗
- 如何在 c++ 中让布尔变量返回为 0 或 1 而不是真或假?
- 从私有成员变量的成员方法返回unique_ptr
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- C++ 根据给定的类型名从变量返回数据
- 为什么 std::isnan() 对于具有 NAN 值的双变量返回 false
- C++ 在静态函数中使用非静态变量返回类实例
- 具有变量返回类型的函数
- 带有 QVariant 和模板的变量返回类型
- getenv() 在不同的程序中为同一环境变量返回不同的值
- C 多重继承,虚拟方法覆盖问题和协变量返回类型
- 变量返回类型
- C++函数向字符串变量返回int
- 从临时变量返回的引用是否有效
- 有没有一种方法可以将C++数据类型作为变量返回
- 类函数的模板变量返回类型
- C++函数,使用'auto'变量返回类型
- 如何将引用变量返回到函数中
- 变量返回类型上转换覆盖c++
- 数组变量返回意外值