def load_csharp(lib_name): try: import clr clr.FindAssembly(lib_name) clr.AddReference(lib_name.split('.')[0]) from DataDriver import DataDriver return DataDriver()
def load_dll(): print("Loading dll...") logging.info("Loading dll...") global AUDIO_CTRL_OBJ sys.path.append("./dlls") clr.FindAssembly("AudioSwitcher.AudioApi.CoreAudio.dll") from AudioSwitcher.AudioApi.CoreAudio import CoreAudioController AUDIO_CTRL_OBJ = CoreAudioController()
def netscan(ip): try: clr.FindAssembly('netscan40.dll') clr.AddReference('netscan40') from LadonDLL import scan print(scan.run(ip)), except: pass
def loadAssemblies(pathList): for t in pathList: path = t[1] if not os.path.exists(path) or not os.path.isfile(path): print("Can't find file: '" + path + "'") continue split = path.rsplit('\\', 1) directoryName = split[0] fileName = split[1] # Add Directory to search dependent assemblies: sys.path.append(directoryName) # Add Assemblie clr.FindAssembly(path) clr.AddReference(t[0]) print("Loaded " + t[0] + " successfully") print("Done loading CLR (.NET) Assemblies")
def __init__(self, ionisation_mode, ref_dir, filename=None, show_console_logs=True, log_dir='C:\\Xcalibur\\data\\Joe\\logs'): super().__init__(ionisation_mode, [], None, add_noise=False) # create IAPI log directory if it doesn't exist self.log_dir = log_dir create_if_not_exist(self.log_dir) # import PythonNet. We will use this to communicate with Thermo IAPI # noinspection PyUnresolvedReferences import clr # noinspection PyUnresolvedReferences from clr import ListAssemblies # add IAPI .dll location to Python path. if ref_dir not in sys.path: sys.path.append(ref_dir) # make sure IAPI assemblies can be found assert clr.FindAssembly('FusionLibrary') is not None ref = clr.AddReference('FusionLibrary') logger.debug('AddReference: %s' % ref) short = list(ListAssemblies(False)) logger.debug('ListAssemblies: %s' % str(short)) assert 'Fusion.API-1.0' in short assert 'API-2.0' in short assert 'Spectrum-1.0' in short assert 'FusionLibrary' in short self.filename = filename self.show_console_logs = show_console_logs self.running_number = 100000 self.fusion_bridge = None self.scan_number_to_params = {}
# coding:utf-8 import clr import sys import win32api import win32con from datetime import datetime from certificate import * sys.path.append("C:\\api") clr.FindAssembly("FiddlerCore4") clr.AddReference("FiddlerCore4") import Fiddler as FC # do some thing when Ctrl-c or colse def onClose(sig): print chr(7) FC.FiddlerApplication.Shutdown() win32api.MessageBox(win32con.NULL, 'See you later', 'Exit', win32con.MB_OK) # will be invoked when it is called by delegate. def printLog(source, oLEA): print "\n** LogString: **\n" + oLEA.LogString def printSession(s): if s is None or s.oRequest is None or s.oRequest.headers is None: return
#python调用c# import clr # pythonnet print('python call K8Cscan c# dll') clr.FindAssembly('netscan.dll') clr.AddReference('netscan') from CscanDLL import * print(scan.run('192.168.1.1')) #scan是netscan.dll中的一个类,run是scan的方法
import logging import clr logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler()) # load the C# .dll supplied by Quantum Design clr.AddReference('QDInstrument') if clr.FindAssembly('QDInstrument') is None: logger.exception('\n\tCould not find QDInstrument.dll') else: logger.exception('\n\tFound QDInstrument.dll at {}'.format( clr.FindAssembly('QDInstrument'))) logger.exception( '\n\tTry right-clicking the .dll, selecting "Properties", and then clicking "Unblock"' ) # import the C# classes for interfacing with the PPMS from QuantumDesign.QDInstrument import QDInstrumentBase, QDInstrumentFactory QDINSTRUMENT_TYPE = { 'DynaCool': QDInstrumentBase.QDInstrumentType.DynaCool, 'PPMS': QDInstrumentBase.QDInstrumentType.PPMS, 'SVSM': QDInstrumentBase.QDInstrumentType.SVSM, 'VersaLab': QDInstrumentBase.QDInstrumentType.VersaLab, 'MPMS': 4121982 } DEFAULT_PORT = 11000
def netscan(ip): clr.FindAssembly('netscan.dll') clr.AddReference('netscan') from CscanDLL import scan print(scan.run(ip))
""" Created on Wed Feb 7 16:52:44 2018 @author: Administrator """ #from win32com.client import Dispatch #mp = Dispatch("MelfaRxM.ocx") import time import clr import System import System.Drawing #import System.Windows.Forms clr.AddReference('System.Windows.Forms') form = System.Windows.Forms.Form() clr.FindAssembly('Interop.MELFARXMLib.dll') # 加载c#dll文件 clr.FindAssembly('AxInterop.MELFARXMLib.dll') # 加载c#dll文件 clr.AddReference('Interop.MELFARXMLib') clr.AddReference('AxInterop.MELFARXMLib') import AxMELFARXMLib ctrMelfaRxM = AxMELFARXMLib.AxMelfaRxM() ((System.ComponentModel.ISupportInitialize)(ctrMelfaRxM)).BeginInit() #a=System.Windows.Forms.Control.ControlCollection.Ctrol form.Controls.Add(ctrMelfaRxM) ((System.ComponentModel.ISupportInitialize)(ctrMelfaRxM)).EndInit() if ctrMelfaRxM.ServerLive() == False: ctrMelfaRxM.ServerStart()
Created on Mon Jan 20 12:56:50 2014 @author: LZM100.00014 """ import sys sys.path.append(r'C:\Users\LZM100.00014\splicer_comm') import clr clr.AddReference("System.Windows.Forms") from System.Windows.Forms import Form, Application c = Form() from System import Reflection full_filename = clr.FindAssembly('UsbFsm100Server') clr.AddReference('UsbCoreFsm100') clr.AddReference('UsbFsm100Server') #print full_filename #Reflection.Assembly.LoadFile(full_filename) #from clr.System.Reflection import Assembly #b = clr.AddReference('UsbFsm100Server') #clr.AddReferenceToFile('UsbFsm100Server.dll') #from clr.UsbFsm100Server import UsbFsm100ServerClass #Application.Run(c) import win32gui def my_handler(source, args):
import clr dll = clr.FindAssembly('MyMath') # returns path to dll assembly = clr.AddReference('MyMath') #print(type(assembly)) # <class 'System.Reflection.RuntimeAssembly'> #print(dir(assembly)) from MyMath import MyMathClass from MyMath import MyMathClass as My assert My.addInts(2, 3) == 5 assert My.addInts(2.7, 7.8) == 9 assert My.addDouble(11.2, 23.3) == 34.5 assert My.addString("hello", "world") == "hello world" assert My.andBool(1, 1) is True assert My.andBool(1, 0) is False assert My.andBool(True, True) is True assert My.andBool(False, True) is False assert My.str_by_index(["apple", "banana", "peach"], 0) == "apple" assert My.str_by_index(["apple", "banana", "peach"], 1) == "banana" assert My.int_by_index([17, 19, 42], 1) == 19 # Mixed list cannot be passed # tuple can be passed assert My.int_by_index((17, 21, 42), 2) == 42 # TODO: string, char, float # TODO strings, lists, dicts, # TODO complex data structures in C# # TODO Async
# encoding: utf-8 import clr #clr.AddReference() #from WindowsFormsTest import Program clr.FindAssembly("WindowsFormsTest.dll") from WindowsFormsTest import * def test(): dd = Form1() dd.ShowDialog() print("被调用") if __name__ == '__main__': test()
import clr import sys from public import config project_path = config.study_case_path sys.path.append(project_path) clr.FindAssembly("TestDemo") # 加载c#dll文件 from TestDemo import * # 导入命名空间 def test(): instance = TestTxt() # TestTxt是dll里面的类 print(instance.GetStr()) # 一个简单的打印 if __name__ == '__main__': test()
import clr, sys, os bin_path = r"C:\Users\LocalAdmin\Documents\GitHub\stchan-sandbox\BarcelonaSweepSGPhase_ContinuousSA\bin" sys.path.insert(1, bin_path) print(clr.FindAssembly("NationalInstruments.Common")) print( clr.AddReference( bin_path + r"\NationalInstruments.ModularInstruments.NIRfsa.Fx45.dll")) print( clr.AddReference( bin_path + r"\NationalInstruments.ModularInstruments.TClock.Fx40.dll")) print( clr.AddReference(bin_path + r"\NationalInstruments.ModularInstruments.Common.dll")) print(clr.AddReference(bin_path + r"\NationalInstruments.Common.dll")) import NationalInstruments.ModularInstruments.NIRfsa as Rfsa import NationalInstruments.ModularInstruments.SystemServices.TimingServices as TClock
#!/usr/bin/python # -*- coding: utf-8 -*- # @Author : {Jan__} # @Time : 2020/10/29 23:41 import os import sys import clr from PyQt5.QtCore import pyqtSignal, QObject FolderPath = os.getcwd() # 获取当前路径 sys.path.append(FolderPath) # 加载当前路径 clr.FindAssembly("Seagull.BarTender.Print.dll") clr.AddReference("Seagull.BarTender.Print") # clr.FindAssembly("mscorlib.dll") # clr.AddReference("mscorlib") from Seagull.BarTender.Print import Engine, Printers, Printer, LabelFormatDocument, Messages, Message, SaveOptions from System import EventHandler class Bartender(QObject): eventSignal = pyqtSignal(str) # 输出信号,用于告知调用者,发送和接受情况 def __init__(self): super(Bartender, self).__init__() self.btEngine = Engine(True) # 创建 BarTender 的 Engine,参数True代表创建时自动调用Start函数 # EventHandler 来自 System,在C#中EventHandler其实是一个模板,由于在python里面不用声明类型所以直接使用了模板 self.btEngine.JobCancelled += EventHandler(self.btEngine_JobCancelledSlot) self.btEngine.JobErrorOccurred += EventHandler(self.btEngine_JobErrorOccurredSlot) self.btEngine.JobMonitorErrorOccurred += EventHandler(self.btEngine_JobMonitorErrorOccurredSlot) self.btEngine.JobPaused += EventHandler(self.btEngine_JobPausedSlot) self.btEngine.JobQueued += EventHandler(self.btEngine_JobQueuedSlot) self.btEngine.JobRestarted += EventHandler(self.btEngine_JobRestartedSlot) self.btEngine.JobResumed += EventHandler(self.btEngine_JobResumedSlot) self.btEngine.JobSent += EventHandler(self.btEngine_JobSentSlot)
import clr import json import sys import System cur_space = sys.path[0] sys.path.append(cur_space) clr.FindAssembly('Simulation.dll') from Simulation import * import Simulation class TestDll(object): """docstring for TestDll""" def __init__(self,): super(TestDll, self).__init__() def main(self, Sa0, Mq0, Ma0, MA0, v0, a, snr, Ri, pj, tMax): track = Track(0, 0) trajectory = Trajectory(0,0,0) location = Location(0,0,0,0,0) distance = Distance(0, 0, 0) maxDD = MaxDD(0, 0) strength = Strength(0, 0) airnoise = Airnoise(0) detectornoise = Detectornoise(0) probability = Probability(0, 0, 0) DR = 0.01745329252 P = 0
import numpy as np import clr import Skype4Py import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore import subprocess as sp import threading as td DATA='' COLUMNS='' try: clr.AddReference('QDInstrument') except: if clr.FindAssembly('QDInstrument') is None: print('Could not find QDInstrument.dll') else: print('Found QDInstrument.dll at {}'.format(clr.FindAssembly('QDInstrument'))) print('Try right-clicking the .dll, selecting "Properties", and then clicking "Unblock"') # import the C# classes for interfacing with the PPMS import QuantumDesign.QDInstrument as QDInstrument #labview=win32com.client.Dispatch('LabVIEW.Application') rm=visa.ResourceManager() k2400_address='GPIB0::24::INSTR' class PPMS(): """Thin wrapper around the QuantumDesign.QDInstrument.QDInstrumentBase class"""
import clr import sys sys.path.append('D:\\svn\\zg\\DirectAD\\LabSys\\CSharpUtils\\Debug') clr.FindAssembly( 'D:\\svn\\zg\\DirectAD\\LabSys\\CSharpUtils\\Debug\\CSharpUtils.dll') clr.AddReference( 'D:\\svn\\zg\\DirectAD\\LabSys\\CSharpUtils\\Debug\\CSharpUtils.dll') from CSharpUtils.ConvertUtils import * from CSharpUtils.HttpUtil import * b = BytesConvert() print(b) print(b.BytesToInt(b'\x01\x00')) i = IpUtil() print(i.Ip_2_Int('127.0.0.1')) print(hex(2130706434)) print(i.Int_2_Ip(2130706434))
# import com dll import clr import platform import sys import os if platform.architecture()[0] == '64bit': sys.path.append( os.path.join(os.path.dirname(os.path.realpath(__file__)), '64bit')) else: sys.path.append( os.path.join(os.path.dirname(os.path.realpath(__file__)), '32bit')) clr.FindAssembly(r"COThermoSocket.Core.dll") from COThermoSocket.Core import * from enum import IntEnum sys.path.append(os.path.dirname(os.path.realpath(__file__))) from uom import * class Phases(IntEnum): Vapor = 0 Liquid = 1 Liquid2 = 2 Solid = 3 Overall = 4 class Bases(IntEnum): Mole = 0 Mass = 1 Undefined = 2
import clr clr.FindAssembly("class1.dll") from ClassLibrary1 import * o = Class1() print(o.Add(5, 6)) # exception try: print(o.Add(-5, 6)) except Exception as e: print(e.Message)
import ctypes import clr import sys # ctypes 加载 C/C++ 的dll # dll = ctypes.WinDLL('./DLL/AudioSwitcher.AudioApi.CoreAudio.dll') # dll = ctypes.WinDLL('./DLL/AudioSwitcher.AudioApi.CoreAudio.dll') sys.path.append("./DLL") # 加载c# dll文件 clr.FindAssembly("AudioSwitcher.AudioApi.CoreAudio.dll") from AudioSwitcher.AudioApi.CoreAudio import CoreAudioController # 导入命名空间 # create object audio_ctrl_obj = CoreAudioController() mic_device = audio_ctrl_obj.DefaultCaptureDevice if mic_device: print("current mic volume is " + str(mic_device.Volume)) mic_device.Volume = 80 else: print('there is not mic device.') speaker_device = audio_ctrl_obj.DefaultPlaybackDevice print("current speaker volume is " + str(speaker_device.Volume)) print('end')
# -*- coding: utf-8 -*- # @Author : {Jan__} # @Time : 2020/4/14 10:32 import datetime as dt import serial import serial.tools.list_ports import clr import os import sys FolderPath = os.getcwd() # 获取当前路径 sys.path.append(FolderPath) # 加载当前路径 clr.FindAssembly("Seagull.BarTender.Print.dll") clr.AddReference("Seagull.BarTender.Print") clr.FindAssembly("mscorlib.dll") clr.AddReference("mscorlib") from Seagull.BarTender.Print import Engine, Printers, Printer, LabelFormatDocument, Messages, Message, SaveOptions from System import EventHandler from app import Ui_Form from PyQt5.QtWidgets import QWidget, QMessageBox, QApplication from PyQt5.QtCore import QTimer class myAutoPrintAppication(QWidget, Ui_Form): def __init__(self): super(myAutoPrintAppication, self).__init__() # 分别调用了2个父类的初始化函数 # UI界面控件的初始化 self.setupUi(self) # 创建 BarTender 的 Engine,参数True代表创建时自动调用Start函数
# @Last Modified by: Yanff # @Last Modified time: 2018-09-24 10:31:08 import numpy as np from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg from pyqtgraph.dockarea import * import OperationCode as OptC import spinapi as spinpy import unit import Config, time import ButtonStyle import constant as spinconst import visa, clr #connect to the MW generator and SR830 clr.FindAssembly('mcl_gen64.dll') from mcl_gen64 import * gen = usb_gen() SN = gen.Connect() SN = gen.SetPowerON() # if (SN == 1 or SN == 2): # print('generator worked well') # else: # print('generator is disabled') # exit() # rm = visa.ResourceManager() # SR850 = rm.open_resource('GPIB0::8::INSTR')
# -*- coding: utf-8 -*- """ Created on Thu Jan 11 20:46:46 2018 @author: Administrator """ # coding=utf-8 ## clr是公共运行时环境,这个模块是与C#交互的核心 import clr #import sys ## 导入clr时这个模块最好也一起导入,这样就可以用AddReference方法 #import System clr.FindAssembly('find.dll') # 加载c#dll文件 clr.AddReference('find') from find import *
""" FileName: visionscript.py Author: [email protected] Create date: 2017.6.20 description: 视觉脚本 Update date:2017.7.20 version 1.0.0 """ import time import threading import systempath import sys import mainsetup import clr clr.FindAssembly(systempath.bundle_dir + '/Vision/BaumerSDKV2.dll') # 加载c#dll文件 from BaumerSDKV2 import * class Vision(): # 实现一个单例类 _instance = None __first_init = True def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance def __init__(self, parent=None): if (self.__class__.__first_init): # 只初始化一次
# -*- coding: utf-8 -*- # clr.FindAssembly方法而不是clr.ADDReference方法,而且导入clr模块时,最好也把System模块导入,原因注释里已经说了,最后注意一点就是一定要把C#的命名空间当做模块导入进来。 import clr # clr是公共运行时环境,这个模块是与C#交互的核心 import sys sys.path.append(r'd:\Code\Test\PythonCall\Lib') # 加载c#dll文件路径 d = clr.FindAssembly('CallLibrary') # 加载c#dll文件 #print(d) a = clr.AddReference('CallLibrary') # 实例化C#类库,这样可以调用,比如这个类库的来源Location #print(a) #from CallLibrary import * # 导入命名空间 #from CallLibrary.Utils import * import CallLibrary as clib class DotNetProj(object): def Call(self): clib.Class1().Start() print('') def Call_Code(self, code): clib.Class1().Start(code) print('') def Call_Return(self, code): ret = clib.Utils.CommonHelper().Start(code) print('') print(ret)
""" Created on Sat Mar 31 17:42:41 2018 @author: Administrator """ import clr import sys import os import numpy as np #import cv2 import System import System.Drawing import cv2 sys.path.append(r'C:\Users\Administrator\Documents\visual studio 2012\Projects\lmidll\lmidll\bin\x86\Release') clr.FindAssembly('lmidll.dll') clr.FindAssembly('GoSdk.dll') clr.FindAssembly('GoSdkNet.dll') clr.FindAssembly('kkApi.dll') clr.FindAssembly('kApiNet.dll') clr.AddReference('kApiNet') clr.AddReference('GoSdkNet') clr.AddReference('lmidll') clr.AddReference('System.Drawing') clr.AddReference('System.IO') clr.FindAssembly('halcondotnet.dll') clr.AddReference('HalconDotNet') from HalconDotNet import * ho_Image=HObject(()) ho_Image=HObject(())
import clr clr.FindAssembly("OBDAutoTestAPI.dll") clr.AddReference('OBDAutoTestAPI') from OBDAutoTestAPI import * from OBDAutoTestAPI.Mode import * class FaultSet(): def __init__(self): self.Api = AutoTestObject() #ClearAllFault def ClearFault(self): return self.Api.ClearCaseFault() # FaultPinShortCircuit(int testType, int pin1, int pin2, int duration, bool scircuitWithPin) # result = mode.FaultPinShortCircuit(0, 1, 1, 1000, False) def PinShortGND(self, pin, scircuitWithPin): return self.Api.FaultPinShortCircuit(2, pin, 0, 0, scircuitWithPin) def PinShor5V(self, pin, scircuitWithPin): return self.Api.FaultPinShortCircuit(1, pin, 0, 0, scircuitWithPin) def PinShortBat(self, pin, scircuitWithPin): return self.Api.FaultPinShortCircuit(0, pin, 0, 0, scircuitWithPin) def PinShorTwoPin(self, pin1, pin2, scircuitWithPin): return self.Api.FaultPinShortCircuit(3, pin1, pin2, 0, scircuitWithPin) ##UpdateTaskWin("start add ressistance test", 5) # FaultPinAddResistance(int testType, int pin, int resisval, int duration)
import clr import ctypes import numpy as np clr.FindAssembly("OlympusNDT.Instrumentation.NET.dll") clr.AddReference('OlympusNDT.Instrumentation.NET') from OlympusNDT.Instrumentation.NET import Utilities, IDeviceDiscovery, DiscoverResult, IFirmwarePackageScanner from OlympusNDT.Instrumentation.NET import UltrasoundTechnology, IAcquisition class FPXDevice(object): def __init__(self, ip_address): Utilities.ResolveDependenciesPath() deviceDiscovery = IDeviceDiscovery.Create(ip_address) discoverResult = deviceDiscovery.DiscoverFor(5000) self.device = discoverResult.device if discoverResult.status == DiscoverResult.Status.DeviceFound: print("Focus PX Device is found!") def download_firmware_package(self, package_name): firmwarePackages = IFirmwarePackageScanner.GetFirmwarePackageCollection() for i in range(firmwarePackages.GetCount()): fw_name = firmwarePackages.GetFirmwarePackage(i).GetName() if fw_name.find(package_name) != -1: print("Firmware Package %s is found!" % fw_name) firmwarePackage = firmwarePackages.GetFirmwarePackage(i) self.device.Start(firmwarePackage) print("Firmware Package is started!") return