我在 Excel 插件 (xll) 中有一个特定的函数。 该插件是专有的,我们无权访问源代码。但是,我们需要调用插件中包含的一些函数,我们希望从 C# 程序中调用它。
目前,我正在考虑编写一个用 xlopers 调用 Excel 函数的 C++ 接口(interface),然后从 C# 调用这个 C++ 接口(interface)。
有没有遇到过此类问题的人知道最好的解决方案是什么?
安东尼
最佳答案
你需要创建一个fake xlcall32.dll,把它和你的XLL放在同一个目录下(不要把excel自带的xlcall32.dll放在PATH里)。这是一些代码:
# include <windows.h>
typedef void* LPXLOPER;
extern "C" void __declspec(dllexport) XLCallVer ( ) {}
extern "C" int __declspec(dllexport) Excel4 (int xlfn, LPXLOPER operRes, int count,... ) { return 0; }
extern "C" int __declspec(dllexport) Excel4v(int xlfn, LPXLOPER operRes, int count, LPXLOPER far opers[]) {return 0;}
现在假设我有一个名为 xll-dll.xll 的 XLL,其中包含一个名为 xlAdd 的函数(使用“depends.exe”找出导出函数的名称),它很好地添加了两个 double 值: extern "C"__declspec(dllexport) XLOPER * __cdecl xlAdd(XLOPER* pA, XLOPER* pB);
下面的代码调用它:
# include <windows.h>
# include <iostream>
// your own header that defines XLOPERs
# include <parser/xll/xloper.hpp>
// pointer to function taking 2 XLOPERS
typedef XLOPER * (__cdecl *xl2args) (XLOPER* , XLOPER* ) ;
void test(){
/// get the XLL address
HINSTANCE h = LoadLibrary("xll-dll.xll");
if (h != NULL){
xl2args myfunc;
/// get my xll-dll.xll function address
myfunc = (xl2args) GetProcAddress(h, "xlAdd");
if (!myfunc) { // handle the error
FreeLibrary(h); }
else { /// build some XLOPERS, call the remote function
XLOPER a,b, *c;
a.xltype = 1; a.val.num = 1. ;
b.xltype = 1; b.val.num = 2. ;
c = (*myfunc)(&a,&b);
std::cout << " call of xll " << c->val.num << std::endl; }
FreeLibrary(h); }
}
int main()
{test();}
我的 exe 确实有效(出乎我的意料),并按预期输出 3。您必须对 XLL 实际期望的参数有所了解。如果它分配了一些内存,你必须检查#define xlbitDLLFree 0x4000 在您的 XLOPER c->type 上设置,并回调“xlAutoFree”。
关于c# - 从 C# 调用 Excel/DLL/XLL 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1940747/