You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenBabel C# HelloWorld程序32/64位环境运行抛出异常如何解决?

问题描述

尝试在64位模式下编译运行OpenBabel官方提供的C#测试程序,测试代码如下:
Program.cs

using System;
using OpenBabel;

namespace MyConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                OBConversion obconv = new OBConversion();
                obconv.SetInFormat("smi");
                OBMol mol = new OBMol();
                obconv.ReadString(mol, "CCC");
                System.Console.WriteLine(mol.GetMolWt());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}

预期输出:

44.09562

OpenBabel针对PC端提供了32位和64位两个不同的安装包,实际运行时出现两类报错:

  1. 32位模式下运行弹出不兼容提示
    32位运行报错截图
  2. 64位模式下运行抛出如下异常:
System.TypeInitializationException: The type initializer for 'OpenBabel.openbabel_csharpPINVOKE' threw an exception.
 ---> System.TypeInitializationException: The type initializer for 'SWIGExceptionHelper' threw an exception.
 ---> System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (0x8007000B)
   at OpenBabel.openbabel_csharpPINVOKE.SWIGExceptionHelper.SWIGRegisterExceptionCallbacks_openbabel_csharp(ExceptionDelegate applicationDelegate, ExceptionDelegate arithmeticDelegate, ExceptionDelegate divideByZeroDelegate, ExceptionDelegate indexOutOfRangeDelegate, ExceptionDelegate invalidCastDelegate, ExceptionDelegate invalidOperationDelegate, ExceptionDelegate ioDelegate, ExceptionDelegate nullReferenceDelegate, ExceptionDelegate outOfMemoryDelegate, ExceptionDelegate overflowDelegate, ExceptionDelegate systemExceptionDelegate)
   at OpenBabel.openbabel_csharpPINVOKE.SWIGExceptionHelper..cctor()
   --- End of inner exception stack trace ---
   at OpenBabel.openbabel_csharpPINVOKE.SWIGExceptionHelper..ctor()
   at OpenBabel.openbabel_csharpPINVOKE..cctor()
   --- End of inner exception stack trace ---
   at OpenBabel.openbabel_csharpPINVOKE.new_OBConversion__SWIG_2()
   at OpenBabel.OBConversion..ctor()
   at MyConsoleApplication.Program.Main(String[] args) in C:\Users\pc\source\repos\Openbabel__test\Program.cs:line 12
解决方案

报错核心原因是项目生成的目标位数与安装的OpenBabel原生库位数不匹配,OpenBabel的C#绑定基于原生库封装,必须和安装的原生库位数完全对应才能正常运行,可按以下步骤修复:

  • 先确认你安装的OpenBabel版本位数,和项目的目标生成位数严格对应:如果装的是64位OpenBabel,项目必须设为x64生成;如果装的是32位OpenBabel,项目必须设为x86生成,不要使用Any CPU模式。
  • 右键打开项目属性页,切换到「生成」选项卡,手动选择对应平台目标,同时取消勾选「首选32位」选项。
  • 把OpenBabel安装目录下的所有dll文件复制到项目的输出目录(默认路径为bin\Debug\对应.NET版本号\),或者把OpenBabel的安装路径添加到系统环境变量PATH中,确保运行时可以找到OpenBabel的核心依赖库。
  • 重新生成项目后运行,即可得到预期输出。

内容的提问来源于stack exchange,提问作者user366312

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 11:27:02