Skip to content

6.1 Python 接入 C99 SDK

概述

Python 应用可通过 ctypes 调用 C99 SDK 动态库,实现跨语言集成。

6.1.1 环境准备

依赖说明
Python3.6+
C99 SDKc_arm_api.dll (Windows) 或 libc_arm_api.so (Linux)

6.1.2 最小示例:连接与断开

python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import ctypes

# 加载 C99 SDK 动态库
arm_api = ctypes.CDLL("c_arm_api.dll")

# 创建句柄
handle = arm_api.Arm_Create()

# 连接机器人
ret = arm_api.Arm_Connect(handle, b"10.27.1.2", b"10.27.1.102")
print(f"连接结果: {ret}")

# 断开连接
arm_api.Arm_Disconnect(handle)

# 销毁句柄
arm_api.Arm_Destroy(handle)
print("完成")

6.1.3 面向对象封装(外观模式)

可以创建一个 Arm 类,将 C99 函数封装成 Pythonic 的面向对象 API:

python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import ctypes

class Arm:
    """机器人控制封装类"""

    def __init__(self, dll_path: str = "c_arm_api.dll"):
        self._api = ctypes.CDLL(dll_path)
        self._setup_signatures()
        self._handle = None

    def _setup_signatures(self):
        """设置函数签名"""
        self._api.Arm_Create.argtypes = []
        self._api.Arm_Create.restype = ctypes.c_void_p

        self._api.Arm_Destroy.argtypes = [ctypes.c_void_p]
        self._api.Arm_Destroy.restype = None

        self._api.Arm_Connect.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p]
        self._api.Arm_Connect.restype = ctypes.c_int

        self._api.Arm_Disconnect.argtypes = [ctypes.c_void_p]
        self._api.Arm_Disconnect.restype = None

    def connect(self, controller_ip: str, teach_panel_ip: str = None) -> None:
        """连接机器人"""
        if self._handle is None:
            self._handle = self._api.Arm_Create()
        ret = self._api.Arm_Connect(
            self._handle,
            controller_ip.encode('utf-8'),
            teach_panel_ip.encode('utf-8') if teach_panel_ip else None
        )
        if ret != 0:
            raise RuntimeError(f"连接失败: {ret}")

    def disconnect(self) -> None:
        """断开连接"""
        if self._handle:
            self._api.Arm_Disconnect(self._handle)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.disconnect()
        if self._handle:
            self._api.Arm_Destroy(self._handle)
        return False

# 使用示例
with Arm() as arm:
    arm.connect("10.27.1.2", "10.27.1.102")
    print("连接成功")

6.1.4 注意事项

  1. 字符串编码:传入字符串需 encode('utf-8') 转为 bytes
  2. DLL 路径:确保 DLL 在可搜索路径中
  3. 线程安全:同一句柄不能跨线程并发访问
  4. BasScript Builder:C99 提供 ArmBasScriptHandle / ArmBasExtraParamHandle ,Python 绑定层可将脚本构造接口封装为对象
  5. Builder 便捷封装Arm_BasScript_SetName / AppendLine(s)Arm_BasValue_* 可映射为 Python 对象方法和 工厂函数