[![pythonC#Exceptions][1]][1]Я вызываю dll C# из Python, а затем загружаю модуль Python v3.11 на испытательный стенд National Instruments. Я получаю одни и те же исключения в Python и на тестовом стенде. Когда я запускаю программу только на C#, проблем нет, она работает так, как должна
Я прикрепил скриншот к ошибке на Python.
Я не знаю, что делать, чтобы найти причину проблемы. Буду признателен за любые предложения, что это может быть. Я знаю, что строки Python — это UTF-8, а C# — это UTF-16, но я попробовал прочитать строку C# в Python, и это сработало. Я не уверен, что это создает проблемы в функции path.combine.
Спасибо
// File:
// NgpvPaths.cs
// Purpose:
// This module methods for accessing application paths to data
////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace NGPV.Common.AppConfig
{
// -------------------------------------------------------------------- //
// This class provides static routines for accessing generic application paths.
//
// ---------------------------------------------------------------
public class ProductPaths
{
/// ----------------------------------------------------------- ///
/// Class constructor.
///
/// -----------------------------------------------------------
static ProductPaths()
{
ReleaseNumber = GetReleaseNumber();
ProgramExecutableFolder = ExpandPathMacros("{ExecutableFolder}");
SetupFolders();
}
public static string ReleaseNumber { get; }
public static string ProgramDataFolder { get; private set; }
public static string ProgramExecutableFolder { get; private set; }
public static string ProgramExecutableDataFolder =>
Path.Combine(ProgramExecutableFolder, _dataFolder);
public static string ProgramExecutableDataJsonFilesFolder => Path.Combine(ProgramExecutableFolder, _dataJsonFiles);
public static string TonesFolder => Path.Combine(ProgramExecutableDataFolder, "Tones");
public static string EnglishFolder => Path.Combine(ProgramExecutableDataFolder, "English");
public static string DefaultVoiceFolder => Path.Combine(EnglishFolder, _voiceFolder);
public static string VoiceSubfolderName => _voiceFolder;
public static string NgpvRoot => Path.Combine(ProgramDataFolder, _ngpvRootFolder);
public static string DataPath => Path.Combine(ProgramDataFolder, _dataFolder);
public static string DoctorsPath => Path.Combine(ProgramDataFolder, _doctorsFolder);
public static string SystemPath => Path.Combine(ProgramDataFolder, _systemFolder);
public static string VoImagesFolder => Path.Combine(DataPath, "Vo Images");
public static string AnimationsFolder => Path.Combine(DataPath, "Animations");
public static string InstalledLanguagesFolder => Path.Combine(ProgramDataFolder, "Locale");
public static string LanguagePackFolder => Path.Combine(_removeableMediaRootFolder, "Language Packs", ReleaseNumber);
public static string ConfigPath => Path.Combine(ProgramDataFolder, _configFolder);
public static string CertificatePath => Path.Combine(ProgramDataFolder, _certificateFolder);
public static string LogPath => Path.Combine(ProgramDataFolder, _logFolder); //TODO rename to AuxiliaryLogPath
public static string EventLogPath => Path.Combine(ProgramDataFolder, _eventLogFolder);
public static string LogArchivePath => Path.Combine(ProgramDataFolder, _logArchiveFolder);
public static string LogArchivePath_Event => Path.Combine(LogArchivePath, _eventLogFolder);
public static string LogArchivePath_Auxiliary => Path.Combine(LogArchivePath, _logFolder);
public static string CaseLogsPath => Path.Combine(ProgramDataFolder, _caseLogsFolder);
public static string DynamicViewsPath => Path.Combine(ProgramDataFolder, (string)Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule?.FileName), "DynamicViews");
public static string ServiceViewsPath => Path.Combine(ProgramDataFolder, (string)Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule?.FileName), "ServiceViews");
#warning FW - Need to dynamically set WindowsLogPath instead of hardcoding. Why can't it be part of ProgramData?
public static string WindowsLogPath => @"D:\Windows\System32\winevt\Logs";
public static string DiagDataPath => Path.Combine(ProgramDataFolder, _eventLogFolder);
public static string ServiceMaintPath => Path.Combine(ProgramDataFolder, "ServiceMaintenance");
public static string UvcsExportBaseFolder => Path.Combine(_removeableMediaRootFolder, "Export");
public static string UvcsImportBaseFolder { get => _removeableMediaRootFolder; }
// The following propeties needs to be validated.
public static string ToolsFolder => Path.Combine(ProgramDataFolder, _toolsFolder);
// -------------------------------------------------------------------- ///
/// This routine sets the static property ProgramDataFolder.
///
/// -----------------------------------------------------------
public static void EstablishProgramDataFolder(string programDataFolder, string releaseNumber = "")
{
ProgramDataFolder = ExpandPathMacros(programDataFolder, releaseNumber);
}
// -------------------------------------------------------------------- //
// Expands the path macros.
//
// --------------------------------------------------------------------
public static string ExpandPathMacros(string filePath, string releaseNumber = "")
{
filePath = filePath.Replace("{ExecutableFolder}",
Path.GetDirectoryName(Process.GetCurrentProcess().MainModule?.FileName));
filePath = filePath.Replace("{ProgramFiles}",
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
filePath = filePath.Replace("{ProgramData}",
Environment.GetEnvironmentVariable(_progDataEnvVariable) ??
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
filePath = filePath.Replace("{ReleaseNumber}", releaseNumber);
return filePath;
}
private static void CreateFolders(string folder)
{
if (!Directory.Exists(folder))
{
_ = Directory.CreateDirectory(folder);
}
}
public static void SetupFolders()
{
bool isConsole = (Environment.GetEnvironmentVariable(_progDataEnvVariable) != null);
string releaseFolder = isConsole ? "" : "\\{ReleaseNumber}"; // Do not include REL_xxxx folder on console
string programDataPath = "{ProgramData}\\Alcon\\NGPV" + releaseFolder;
ProgramDataFolder = ExpandPathMacros(programDataPath, ReleaseNumber);
// Create all folders if they do not exist
CreateFolders(ProgramDataFolder);
CreateFolders(DoctorsPath);
CreateFolders(SystemPath);
CreateFolders(ConfigPath);
CreateFolders(DataPath);
CreateFolders(LogPath);
CreateFolders(DiagDataPath);
CreateFolders(ToolsFolder);
CreateFolders(EventLogPath);
CreateFolders(LogArchivePath);
CreateFolders(LogArchivePath_Event);
CreateFolders(LogArchivePath_Auxiliary);
}
private static string GetReleaseNumber()
{
Assembly assembly = Assembly.GetEntryAssembly();
FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
return "REL_" + fileVersionInfo.ProductMajorPart.ToString("00") + "." + fileVersionInfo.ProductMinorPart.ToString("00");
}
/// -----------------------------------------------------------
/// Constants
/// -----------------------------------------------------------
private const string _progDataEnvVariable = @"AlconProgramData";
private const string _ngpvRootFolder = @"Alcon\NGPV";
private const string _removeableMediaRootFolder = @"Alcon\UVCS";
private const string _configFolder = "Configurations";
private const string _certificateFolder = "Certificates";
private const string _dataFolder = "Data";
private const string _dataJsonFiles = "DataJsonFiles";
private const string _doctorsFolder = @"Doctors\";
private const string _systemFolder = @"System\";
private const string _toolsFolder = "Tools";
private const string _logFolder = "AuxiliaryLogs";
private const string _eventLogFolder = "EventLogs";
private const string _logArchiveFolder = "_LogArchive";
private const string _caseLogsFolder = "CaseLogs";
private const string _voiceFolder = "Audio";
}
}
import pythonnet
import os
pythonnet.load("coreclr")
import clr
import sys
#USING PYTHONNET LIBRARY
class CSharpAsmblyRefs:
releaseNum = ""
def __init__(self):
assembly_Config_path = (r"C:\\source\\repos\\Host\\Tools\\TestFramework.Test\\bin\\x64\\Debug\\net6.0-windows\\")
assembly_CSharpdll_path = (r"C:\\python311\\modules\\python_env2\\")
sys.path.append(assembly_CSharpdll_path)
clr.AddReference("ScriptingClientLib")
clr.AddReference("NGPV.Common.ProtoDefinition")
clr.AddReference("NGPV.Common.RPC")
clr.AddReference("NGPV.Common.TraceListener")
clr.AddReference("NGPV.Common.UIBase")
clr.AddReference("ScriptingCommander")
clr.AddReference("Diag")
clr.AddReference("NGPV.Common.AppConfig")
from ScriptingClientLib import ScriptingClient
clr.AddReference("NGPV.Common.AppConfig")
from NGPV.Common.AppConfig import ProductPaths
sys.path.append(assembly_Config_path)
clr.AddReference("System.Configuration.ConfigurationManager")
from System.Configuration import ConfigurationManager
scrptClient = ScriptingClient()
scrptClient.RunAsync("Initialize.csx")
Теперь я получаю эти ошибки в Python, когда исключаю вызов статической функции GetRealeaseNumber в конструкторе C# ProductPaths.cs: Похоже, теперь он ищет Grpc.core для версии 2.0. .0. У меня только v2.42.0 и v2.46.6
Traceback (most recent call last):
File "C:\Python311\Modules\python_env2\CSharpdll_pythonnet_Class.py", line 82, in
sc = CSharpAsmblyRefs()
File "C:\Python311\Modules\python_env2\CSharpdll_pythonnet_Class.py", line 51, in __init__
scrptClient.RunAsync("Initialize.csx")
System.IO.FileNotFoundException: Could not load file or assembly 'Grpc.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=d754f35622e28bad'. The system cannot find the file specified.
File name: 'Grpc.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=d754f35622e28bad'
at NGPV.Common.Diag.ScriptingCommander..ctor(String host, Int32 port)
at ScriptingClientLib.ScriptPackageViewModel..ctor()
at ScriptingClientLib.ScriptPackageViewModel.get_Instance()
at ScriptingClientLib.ScriptingClient.RunAsync(String csxFileName)
at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)
Подробнее здесь: https://stackoverflow.com/questions/785 ... -func-from
TypeInitializationException/NullReferenceException вызывает функцию C# dll из pythonnet. Стек вызовов показывает, что ис ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение