powered by simpleCommunicator - 2.0.51     © 2025 Programmizd 02
Форумы / WPF, Silverlight [игнор отключен] [закрыт для гостей] / Ошибка импорта dll ArithmeticException
5 сообщений из 5, страница 1 из 1
Ошибка импорта dll ArithmeticException
    #38814600
Импортирую dll-ку:

[DllImport("EEG4DLL.DLL", CallingConvention = CallingConvention.StdCall)]
private static extern string return_text_error(uint error);


При вызове

MessageBox.Show(return_text_error(5));

Ее значение возвращается, а потом вызывается исключение System.ArithmeticException "Переполнение или потеря точности в арифметической операции"

System.ArithmeticException не обработано
HResult=-2147024362
Message=Переполнение или потеря точности в арифметической операции.
Source=mscorlib
StackTrace:
в System.Double.IsPositiveInfinity(Double d)
в System.Windows.Window.ValidateTopLeft(Double length)
в System.Windows.Window.CoerceTop(DependencyObject d, Object value)
в System.Windows.DependencyObject.ProcessCoerceValue(DependencyProperty dp, PropertyMetadata metadata, EntryIndex& entryIndex, Int32& targetIndex, EffectiveValueEntry& newEntry, EffectiveValueEntry& oldEntry, Object& oldValue, Object baseValue, Object controlValue, CoerceValueCallback coerceValueCallback, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, Boolean skipBaseValueChecks)
в System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
в System.Windows.DependencyObject.CoerceValue(DependencyProperty dp)
в System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight)
в System.Windows.Window.CreateSourceWindow(Boolean duringShow)
в System.Windows.Window.CreateSourceWindowDuringShow()
в System.Windows.Window.SafeCreateWindowDuringShow()
в System.Windows.Window.ShowHelper(Object booleanBox)
в System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
в MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
в System.Windows.Threading.DispatcherOperation.InvokeImpl()
в System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
в System.Windows.Threading.DispatcherOperation.Invoke()
в System.Windows.Threading.Dispatcher.ProcessQueue()
в System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
в MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
в MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
в System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
в MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
в System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
в MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
в MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
в System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
в System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
в System.Windows.Threading.Dispatcher.Run()
в System.Windows.Application.RunDispatcher(Object ignore)
в System.Windows.Application.RunInternal(Window window)
в System.Windows.Application.Run(Window window)
в System.Windows.Application.Run()
в WpfEEG.App.Main() в C:\Users\user\Documents\Visual Studio 2010\Projects\EEG\WpfEEG\obj\x86\Debug\App.g.cs:строка 0
в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
в System.Threading.ThreadHelper.ThreadStart_Context(Object state)
в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
в System.Threading.ThreadHelper.ThreadStart()
InnerException:


Как лечить? Пытался изменить CallingConvention - Cdecl вызывает ошибку PInvokeStackImbalance. В обычном C# Windows Form все работает.
...
Рейтинг: 0 / 0
Ошибка импорта dll ArithmeticException
    #38814611
bazile
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Алексей Вахтин, возможно проблема возникает при маршаллинге возвращаемой строки и надо указать атрибут [return: MarshalAs(UnmangedType.????)] для функции.
...
Рейтинг: 0 / 0
Ошибка импорта dll ArithmeticException
    #38814652
Нет, не помогает. И вообще, эта проблема возникает при вызове любой функции из этой библиотеки. Потому как я столкнулся с ней при вызове функции

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
        [DllImport("EEG4DLL.DLL")]
        private static extern void SetErrorFunction(delegate_func_user_error func_user_error);

        private delegate void delegate_func_user_error(uint error, uint type_error);

..............

            d_func_user_error = new delegate_func_user_error(func_user_error);
            SetErrorFunction(d_func_user_error);



И та же самая ошибка при вызове функции без параметров:

Код: c#
1.
2.
        [DllImport("EEG4DLL.DLL")]
        private static extern void SwitchOff();
...
Рейтинг: 0 / 0
Ошибка импорта dll ArithmeticException
    #38814655
Проблема, видимо, связана с библиотеками StdCall, так как я сейчас попробовал вызвать функции из библиотеки скомпилированной под директивой C:

Код: c#
1.
2.
3.
4.
5.
6.
        [DllImport("CUFT.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern string cuftGetErrorString(int errorCode);

.......................

            MessageBox.Show(cuftGetErrorString(4));



и все прошло без ошибок. Но проблема в том, что EEG4DLL.DLL - не моя библиотека, я не могу ее перекомпилировать. И под атрибутом CallingConvention = CallingConvention.Cdecl она вообще не работает.
...
Рейтинг: 0 / 0
Ошибка импорта dll ArithmeticException
    #38815663
Ошибка появляется, оказывается, если запускать функции в конструкторе или в обработчике события Load. А если сделать вызов функции в другом потоке, то все работает нормально:

[CSHARP] ///Функция вызываемая из потока
private void _SetErrorFunction(object obj)
{
MessageBox.Show(return_text_error(4));
}

..............

private void Window_Loaded(object sender, RoutedEventArgs e)
{
.........................

(new SynchronizationContext()).Post(_SetErrorFunction, null);
}
[/CSHARP]

Вот только не знаю почему
...
Рейтинг: 0 / 0
5 сообщений из 5, страница 1 из 1
Форумы / WPF, Silverlight [игнор отключен] [закрыт для гостей] / Ошибка импорта dll ArithmeticException
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]