【问题标题】:objective-c call python method with multiple parameters use py2app and pyobjcObjective-c 调用带有多个参数的 python 方法使用 py2app 和 pyobjc
【发布时间】:2020-07-23 04:00:33
【问题描述】:

我在 10.15.6 的 macOS 上进行测试,希望 obJC 可以调用 Python。但到目前为止我遇到了一些问题:

我可以使用 PyobJC 在 Python 中引入 OBJC,并使用 Py2App 将 Python 程序打包为“.plugin”插件。

这都不是问题,但是当从 OBJC 调用 python 的多参数方法之一时,Cocoa 应用程序崩溃了

这是我的代码:

python 程序:

setup.py

"""
This is a setup.py script generated by py2applet

Usage:
    python setup.py py2app
"""

from setuptools import setup

APP = ['CLPYTry.py']
DATA_FILES = []
OPTIONS = {}

setup(
    plugin=APP,
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)

CLPYTry.py

import objc
from Cocoa import NSObject

class CLPYTry(NSObject):
    def init(self):
        self = super(CLPYTry, self).init()
        return self

    # @objc.signature('@@:@')
    def doSomeThing_(self, aString):
        return aString + " Handled!"

    # @objc.signature('i@:i:i')
    def doSomeThing2_int2_(self, aInt, aInt2):
        return aInt + 100 + aInt2

CLPYTry 也有这个 Objc 模板代码:

CLtry.h:

//
//  SympyTry.h
//  ObjcPy_Draw
//

#ifndef SympyTry_h
#define SympyTry_h

#import <Foundation/Foundation.h>

@interface CLTry : NSObject

- (NSString *)doSomeThing:(NSString *)string;

- (int)doSomeThing2:(int)integer int2:(int)aint2;

@end

#endif /* SympyTry_h */

我执行了这个 objc 程序:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    
    NSBundle * pluginBundle =  [NSBundle bundleWithPath:@"/Users/XXX/Desktop/ObjcPy_Draw/ObjcPy_Draw/Python_Plugin/dist/CLPYTry.plugin"];

    Class pyClass = [pluginBundle classNamed:@"CLPYTry"];
    CLTry * py = [[pyClass alloc] init];
    NSLog(@"%@", [py doSomeThing:@"a string"]);
    NSLog(@"%d", [py doSomeThing2:10 int2:10]);
}

当我执行 "NSLog(@"%d", [py doSomeThing2:10 int2:10]);"行,可可程序崩溃并抛出错误“线程1:EXC_BAD_ACCESS(代码= 1,地址= 0xa)” 控制台输出:

2020-07-23 11:42:55.054028+0800 ObjcPy_Draw[6214:181410] a string Handled!

显然,这样的直接调用是不可能的。那么,objc如何调用python的多参数方法呢?

我们将不胜感激地接受任何帮助。

【问题讨论】:

    标签: py2app pyobjc


    【解决方案1】:

    除非你做一些特别的事情,否则你的 Python 类的 Objective-C 声明应该是:

    @interface CLTry : NSObject
    
    - (NSString *)doSomeThing:(NSString *)string;
    
    - (NSObject*)doSomeThing2:(NSObject*)integer int2:(NSObject*)aint2;
    
    @end
    

    也就是说,带有 2 个参数的方法应该在其签名中使用 Cocoa 类而不是普通的 C 类型。可以通过显式创建 objc.selector 实例来声明具有不同签名的 Python 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-24
      • 2013-05-29
      • 2014-09-17
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      相关资源
      最近更新 更多