在 Autohotkey 中调用自定义 C#/.Net DLL

col*_*rtz 4 c# dll autohotkey

我想我有点不知所措,但想知道是否有人能指出我正确的方向。我在 Visual Studio 2010 中创建了一个 C# 类库 (dll) 来与 MS SQL 服务器交互。当我从另一个 C# 程序调用它时,它工作正常。但是,当我尝试从 AHK 脚本调用它时,我得到“错误级别 = -4”,表明无法找到该函数。

这是我的 C# 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace AHK_Interface
{
    public class AHK_Interface
    {
        public string TrackUsage()
        {
            try
            {
                SqlConnection ahk_connection = new SqlConnection("Data Source=SQLServer;Initial Catalog=AHK;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
                SqlCommand cmd;
                ahk_connection.Open();
                cmd = new SqlCommand("INSERT INTO AHK_USAGE(username,script_version,notes) VALUES ('TEST user','1.01','TEST NOTES')",ahk_connection);
                cmd.Connection = ahk_connection;
                cmd.ExecuteNonQuery();
                string success_ind = "success!";
                ahk_connection.Close();
                return success_ind;
            }
            catch (Exception e)
            {
                string success_ind = e.Message;
                return success_ind;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我进入regasm.exe并成功注册了DLL。

这是我试图调用它的 Autohotkey 代码。该方法所做的只是执行和插入语句并返回成功/不成功字符串,因此我认为不需要向它传递任何参数。

SetWorkingDir %A_ScriptDir%
DllCall("LoadLibrary", "str", "AHK_Interface.dll")
msgbox %ErrorLevel% ;good at this point
success_ind := DllCall("AHK_Interface\TrackUsage") ;trying to call my method "TrackUsage" above
MsgBox, %success_ind% %ErrorLevel% ;gives error level of -4 here

ExitApp
Run Code Online (Sandbox Code Playgroud)

Joh*_*dal 5

有点晚了,但我遇到了同样的问题,通过使用建议的评论,它起作用了。

我就是这样做的:

1) 使 C# 类静态。

2) 如前所述,使用“UnmanagedExports”。

3) 确保在 dll 调用中使用 DllExport 名称,如下所示:

[DllExport("add", CallingConvention = CallingConvention.Cdecl)]
public static string TrackUsage()
{...}
Run Code Online (Sandbox Code Playgroud)

4)然后通过以下方式调用dll:

dataVariable := DllCall("AHK_Interface\add", "Cdecl Str")
Run Code Online (Sandbox Code Playgroud)