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

使用PythonNet初始化IDispenser接口时遇TypeError错误求助

解决PythonNet实例化IDispenser接口时的TypeError问题

错误信息

Traceback (most recent call last):
    x = IDispenser()
TypeError: interface takes exactly one argument

问题代码

import clr
import sys

dll_path = "C:\\Program Files\\Seyonic\\Dispenser Control Monitor 3.8"

if dll_path not in sys.path:
    sys.path.append("C:\\Program Files\\Seyonic\\Dispenser Control Monitor 3.8")

assert dll_path in sys.path

clr.AddReference("Seyonic.Dispenser")
from Seyonic.Dispenser import IDispenser

x = IDispenser()

DLL接口定义

namespace Seyonic.Dispenser
{
public interface IDispenser
{
// ----------------------------------------------------------------------------
// Properties
// ----------------------------------------------------------------------------
int Data { get;}
...etc
}
}

解决方案

  • .NET接口本身不能直接实例化,PythonNet严格遵循.NET的类型规则,这就是报错的根本原因。
  • 你需要找到IDispenser接口的具体实现类,通常这类设备控制DLL会提供对应的实体类(比如Dispenser),或者工厂方法来创建实例。
  • 示例修改代码(假设存在实现类Dispenser):
import clr
import sys

dll_path = "C:\\Program Files\\Seyonic\\Dispenser Control Monitor 3.8"
if dll_path not in sys.path:
    sys.path.append(dll_path)

clr.AddReference("Seyonic.Dispenser")
from Seyonic.Dispenser import Dispenser  # 替换为实际的实现类名称

x = Dispenser()
# x可直接调用IDispenser接口定义的属性和方法
print(x.Data)
  • 若不确定实现类名称,可通过反射遍历程序集查找:
import clr
clr.AddReference("Seyonic.Dispenser")
from Seyonic.Dispenser import IDispenser
from System import Type

interface_type = IDispenser[Type]
# 遍历程序集中所有非接口类型,筛选实现了IDispenser的类
for type in interface_type.Assembly.GetTypes():
    if interface_type.IsAssignableFrom(type) and not type.IsInterface:
        print(f"找到实现类: {type.FullName}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 20:15:41