На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
Страницы: (3) 1 [2] 3  все  ( Перейти к последнему сообщению )  
> Проблемы с подключением библиотеки
    static это просто аналогия.
    Вот статья из MSDN:

    A __gc array is a dynamic array that is allocated on the common language runtime heap. The number of elements of the array is not part of the type. A single array variable may refer to arrays of different sizes.
    Example
    // __gc_arrays.cpp
    // compile with: /clr
    #using <mscorlib.dll>
    using namespace System;

    int main() {
      Int32 ia[] = __gc new Int32[100];
      ia = new Int32[200];
    }
    The indices of a __gc array are zero-based, as in standard C++. A __gc array is subscripted using ordinary C++ array brackets. Unlike standard C++, subscripting is not a synonym for pointer arithmetic, and is not commutative.
    Characteristics
    A __gc array shall be allocated using the managed operator __gc new.
    Using new to allocate a managed array defaults to __gc new.
    Constraints
    The type of an element of a __gc array shall only be a __value class, or a __gc pointer to a __gc class.
    __nogc new shall not be used to allocate an array of managed type.
    A __gc array variable definition shall not specify a size. The size of the array is given in the call to the managed operator __gc new.
    A __gc array is itself a __gc object. It is actually a pointer into the common language runtime heap. The indirection of the pointer has been factored into the subscripting operator. As a __gc object, it has the same restrictions as a __gc class (Section 4). Most notably, the element type cannot be an unmanaged C++ class that is not a POD type.
    All __gc arrays inherit from System::Array. Any method or property of System::Array can be applied directly to the array variable.
    Example
    // __gc_arrays2.cpp
    // compile with: /clr
    #using <mscorlib.dll>
    using namespace System;

    int main() {
      Int32 ia[] = __gc new Int32[100];
      Console::WriteLine(ia->Length);
    }
    Output
    100
      Кстати я в своём примере ошибся - нельзя использовать встроенный C++ класс double, нужно исползовать FCL класс Double
        Синтаксис допускает оба варианта
        Главное не забыть про /clr и разумеется не пытаться создавать __gc массивы на стеке
          Уважаемый господин Андрей, читал я МСДН и ничего там не понял.

          А для ключа /clr есть аналог в Options?
            Цитата andrey, 30.07.03, 23:26:44
            ... __gc это storage класс, как static или register. Соответственно его надо указывать там где ДОЛЖЕН появляться storage-класс. Или, для __gc arrays ПЕРЕД словом new при выделении памяти ...

            Мне не нужно выделять память для массива. Прочитайте мои вопрос внимательнее. Мне необходимо получить его в качестве параметра функции в библиотеке, которую вызывают из VB.NET. Именно поэтому существует проблема несоответствия типов данных.
              Цитата neutrino, 03.08.03, 20:32:17
              Уважаемый господин Андрей, читал я МСДН и ничего там не понял.
              А для ключа /clr есть аналог в Options?

              Есть там что-то типа Compile managed code.
              И приведи ты в конце-концов ошибки-то.
                Я никак не возьму в толк, тебе нужен ответ на вопрос или нет? Тогда напиши то что тебя просит модератор - то есть ошибки.

                Я попробовал так :
                C++ managed code class library:
                ExpandedWrap disabled
                  <br>class sss{<br>...<br>      public : void PTest(Double arr[]){<br>                         Console::WriteLine(arr->ToString());<br>                   }<br>


                VB.NET windows forms application:
                ExpandedWrap disabled
                  <br>    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load<br>        Dim ss As tst.sss<br>        ss = New tst.sss<br>        Dim mm() As Double<br>        mm = New Double(2) {2.2999999999999998, 5.5999999999999996, 5.2999999999999998}<br>        ss.PTest(mm)<br>    End Sub<br><br>


                У меня всё это работает
                Сообщение отредактировано: kl -
                  Доброго времени суток.
                  Вот вывод компилятора (команда вызова в самом начале):
                  Цитата

                  C:\Documents and Settings\neutrino\My Documents\Heuristics32>cl /clr Heuristics32.cpp
                  Microsoft ® 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86
                  Copyright © Microsoft Corp 1984-1998. All rights reserved.

                  Command line warning D4002 : ignoring unknown option '/clr'
                  Heuristics32.cpp
                  Heuristics32.cpp(37) : fatal error C1021: invalid preprocessor command 'using'

                  C:\Documents and Settings\neutrino\My Documents\Heuristics32>

                  То есть ни параметр '/clr' ни директиву препроцессора '#using' он не понял. Саму эту директиву, как

                  написано в MSDN, надо указывать всегда при использовании Managed C++:
                  Цитата

                  #using <mscorlib.dll>

                  Для полноты картины приведу релевантный кусок кода, который я пытался компилировать:
                  Цитата

                  #include <windows.h>
                  #using <mscorlib.dll>

                  typedef struct City {
                       unsigned int Data;
                       struct City *Next, *Prev;
                  } TCity;

                  TCity *Head=NULL, *Tail=NULL, *Last; // Pointer to the head and tail of list
                  double Distance __gc[,]; // Pointer to distances matrix
                  int Num; // Number of cities

                  BOOL APIENTRY DllMain( HANDLE hModule,
                                        DWORD  ul_reason_for_call,
                                        LPVOID lpReserved
                                                )
                  {
                     switch (ul_reason_for_call)
                       {
                             case DLL_PROCESS_ATTACH:
                             case DLL_THREAD_ATTACH:
                             case DLL_THREAD_DETACH:
                             case DLL_PROCESS_DETACH:
                                   break;
                       }
                     return TRUE;
                  }

                  void DestroyList() {
                       TCity *C=Head, *T;
                       while (C!=Tail) {
                             T=C;
                             C=C->Next;
                             delete T;
                       }
                       delete C;
                  }

                  void SetDistancesMatrix(double M __gc[,]) {
                       Distance=M;
                  }

                  void SetData(unsigned int CitiesData __gc[], unsigned int Pos, unsigned int N) {
                       TCity *C;
                       Num=N;
                       Head=new TCity;            Tail=new TCity;            Last=Head;
                       Head->Data=0;            Tail->Data=0;
                       for (unsigned int i=Pos; i<Pos+Num; i++) {
                             C=new TCity;
                             C->Data=CitiesData[i];
                             C->Prev=Last;
                             Last->Next=C;
                             Last=C;
                       }
                       Tail->Prev=Last;      Last->Next=Tail;
                  }

                  int GetData(unsigned int CitiesData __gc[]) {
                       int Idx=0;
                       TCity *C=Head->Next;
                       while (C!=Tail) {
                             CitiesData[Idx++]=C->Data;
                             C=C->Next;
                       }
                       return Idx-1;
                  }

                  .
                  .
                  .
                    Версия компилера не та, должна быть (у меня такая) 13.0.9466 for .NET Framework.
                    Это MC++ компилятор из MSVS.NET 2003. Если у тебя стоит MSVS.NET, то проверь PATH, может вызывается не тот компилер который надо.
                      Я понимаю, что это наглость, но не мог бы кто-нибудь откомпилировать мой проэкт библиотеки? Пожалуйста. Мне больше ничего не остается делать...

                      Зазипинный проэкт библиотеки: Heuristics.zip (362Kb)
                        Не качается.... Кинь мне на мыло andreyaz ____ @ ____ rol.ru (_ удалить)
                          Отправил.
                            Ээээ, размер файла =0.
                            О, зато теперь качается по ссылке!
                              Блин, там что сервак на модеме сидит?

                              Миллион ошибок.
                              Я отключил все RTC, Debug info, PCH

                              Всё вынесено в класс statics неймспейса ____Heuristics. Ко всему применён модификатор static. DllMain убит нафиг.
                              Количество размерностей массива Distance теперь 1 (при объявлении обявлялось 2, а потом в коде использовалась только 1, соответственно SetDistancesMatrix принимает только 1 мерный массив)

                              Вобщем работать может быть будет.

                              Самое главное: теперь это managed dll и LoadLibrary не катит!
                                Качай http://www.ve-2-00.ru/xxxx.rar
                                0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
                                0 пользователей:
                                Страницы: (3) 1 [2] 3  все


                                Рейтинг@Mail.ru
                                [ Script execution time: 0,0716 ]   [ 17 queries used ]   [ Generated: 25.04.24, 08:10 GMT ]