问题描述
我试图通过方法XlCall.TryExcel从excelDna调用xlfCaller,有时我得到XlReturnStackOvfl,我发现了一些解决此问题的方法:1。在此站点:https://docs.microsoft.com/en-us/office/client-developer/excel/xlfcaller,它表示必须在xlfCaller,2之后在https://docs.excel-dna.net/excel-c-api/处调用xlFree。它表明“ Excel-DNA负责C API调用的所有类型转换和内存管理。 ”,所以我想知道,我需要致电xlFree吗?
解决方法
excelDna总是在调用excel c API之后再调用xlFree,因此我们无需再次调用xlFree。下面是excelDna的源代码:
private unsafe static int TryExcelImpl4(int xlFunction,out object result,params object[] parameters)
{
int xlReturn;
// Set up the memory to hold the result from the call
XlOper resultOper = new XlOper();
resultOper.xlType = XlType.XlTypeEmpty;
XlOper* pResultOper = &resultOper; // No need to pin for local struct
// Special kind of ObjectArrayMarshaler for the parameters (rank 1)
using (XlObjectArrayMarshaler paramMarshaler = new XlObjectArrayMarshaler(1,true))
{
XlOper** ppOperParameters = (XlOper**)paramMarshaler.MarshalManagedToNative(parameters);
xlReturn = Excel4v(xlFunction,pResultOper,parameters.Length,ppOperParameters);
}
// pResultOper now holds the result of the evaluated function
// Get ObjectMarshaler for the return value
ICustomMarshaler m = XlObjectMarshaler.GetInstance("");
result = m.MarshalNativeToManaged((IntPtr)pResultOper);
// And free any memory allocated by Excel
Excel4v(xlFree,(XlOper*)IntPtr.Zero,1,&pResultOper);
return xlReturn;
}