VBA无法找到C#dll入口点

时间:2015-05-08 13:29:55

标签: c# vba dll com-interop

我在C#中创建一个dll,在调用单个函数runSimulation()时运行模拟。应该从VBA调用此dll,因为某些参数值在Excel中作为输入给出。这是我使用的代码。

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using RGiesecke.DllExport;

namespace Simulation
{
    public static class Simulation
    {
        [ComVisible(true)]
        [DllExport("runSimulation", CallingConvention = CallingConvention.Cdecl)]
        [return: MarshalAs(UnmanagedType.SysInt)]
        public static int runSimulation()
        {
            // Do simulation

            return 0;
        }
    }
}

上面的代码被编译为类库,x64作为平台目标,并返回Simulation.dll。

VBA:

Public Declare Function runSimulation Lib "Simulation.dll" () As Long

Sub Run_DLL()
ChDir (ActiveWorkbook.Path)
Dim returnValue As Long
returnValue = runSimulation()
End Sub

运行Visual Basic代码返回

  

运行时错误453:'无法在中找到DLL入口点runSimulation   Simulation.dll'

当它试图调用runSimulation()时。

作为参考:我尝试使用

运行
[DllExport("runSimulation", CallingConvention = CallingConvention.StdCall)]
相反,但这也不起作用。我还尝试使用https://www.linkedin.com/grp/post/40949-258782989中给出的建议,但它给了我同样的错误。

1 个答案:

答案 0 :(得分:2)

我设法在VBA代码中调用'runSimulation'函数,方法是通过C#中的接口公开Simulation类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace NSSimulation
{
    public interface ISimulation
    {
        int runSimulation();
    }

    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public class Simulation : ISimulation
    {
        [ComVisible(true)]
        public int runSimulation()
        {
            return 0;
        }
    }
}

然后重新编译项目并使用'tlbexp.exe'从Visual Studio命令提示符导出重建的库:

tlbexp.exe SimulationLib.dll /out:"SimulationLib.tlb" /win64

然后在Excel中打开Visual Basic编辑器并通过“Tools-> References-> Browse”添加对'SimulationLib.tlb'的引用。验证

Public x As New SimulationLib.Simulation

Sub test()
   MsgBox x.runSimulation
End Sub