gpt4 book ai didi

c# - C++ 库问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:57:15 25 4
gpt4 key购买 nike

我正在尝试从我的 C# 代码调用 C++ 库。我还有一个用 C++ 编写的示例应用程序,它调用同一个库,并且运行良好。但是,来自 C# 的调用会引发错误:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

C#代码是:

#region DllImports

[DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);

[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
static extern IntPtr GetProcAddress(int hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

[DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
static extern bool FreeLibrary(int hModule);

[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
delegate string bondProbeCalc(string licenseFolder, string requestString);

#endregion


/// <summary>
/// Calls Bondprobe to calculate a formula
/// </summary>
internal static string DoBondProbeOperation(string requestString)
{
if (string.IsNullOrEmpty(requestString)) throw new ArgumentNullException();

//Reference library
int hModule = LoadLibrary(ConfigurationManager.Instance.BondProbeSettings.AssemblyFilePath);

if (hModule != 0)
{
IntPtr intPtr = GetProcAddress(hModule, "bpStringCalc");

bondProbeCalc funcDelegate = (bondProbeCalc)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(bondProbeCalc));

requestString = requestString.EndsWith("=") ? requestString.Substring(0, requestString.Length - 1) : requestString;

string returnValue = funcDelegate(ConfigurationManager.Instance.BondProbeSettings.LicenseFilePath, requestString);

FreeLibrary(hModule);

return returnValue;
}

return string.Empty;
}

这段完全相同的代码在某些计算机上有效,但在其他计算机上会抛出错误。但是,示例 C++ 应用程序似乎无处不在。

有什么想法吗?

谢谢,贡萨洛

最佳答案

我猜崩溃发生在运行 64 位操作系统的计算机上。我不知道你的 DoBondProbeOperation 逻辑,但你的 PInvoke 方法应该定义如下:

[DllImport("kernel32.dll", CharSet = CharSet.Auto]
static extern IntPtr LoadLibrary(string lpFileName);

[DllImport("kernel32.dll"]
static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);

[DllImport("kernel32.dll"]
static extern bool FreeLibrary(IntPtr hModule);

hModule0 进行比较,而不是将其与 IntPtr.Zero 进行比较

编辑:修复了 LoadLibraryCharSet

EDIT2:同时尝试将您的 bondProbeCalc 定义更改为以下内容:

[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
delegate string bondProbeCalc(string licenseFolder, string requestString);

或者:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate [MarshalAs(UnmanagedType.LPStr)] string bondProbeCalc([MarshalAs(UnmanagedType.LPStr)] string licenseFolder, [MarshalAs(UnmanagedType.LPStr)] string requestString);

关于c# - C++ 库问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5162544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com