荔园在线

荔园之美,在春之萌芽,在夏之绽放,在秋之收获,在冬之沉淀

[回到开始] [上一篇][下一篇]


发信人: Peter (小飞侠), 信区: Program
标  题: C++ Builder常见问题解答(3)
发信站: BBS 荔园晨风站 (Fri Jan 22 13:52:18 1999), 转信


Question:
BC++ 5.02 and C++Builder do not allow sizeof() to take
a template parameter. How do I get around this?

Answer:
The behavior is a result of a bug in BC++ 5.02 and C++Builder.
Borland is aware of the bug. In the interim, the following hack
will get around the problem:

template <class T> class foo {
    struct hack {T t; };
    enum _sz {SIZE = sizeof(t) };
}

2、Calling Pascal from C++Builder

Question:
How do I call Pascal routines and variables from C++ modules?

Answer:
   An easy way to find out is to let C++Builder do it for you.
Put the Object Pascal declarations you need to translate in the
interface section of an Object {ascal unit.  Now use the command
line compiler DCC32.EXE with the options j, p, h, n, and v.
Below is an example of called DCC32 to translate a file called
MyUnit.pas.

        DCC32 -jphnv  MyUnit.pas

After the compliler finished you will have a header file call
MyUnit.hpp, open it in an editor and will see the C++
declarations.

3、Converting AnsiString to numeric variables

Question:
   How do you convert AnsiStrings to and from numeric values in
C++Builder?

Answer:
   Use the built-in functions StrToInst() and StrToFloat convert
to numeric values and IntToStr() and StrToFloat() for the
reverse process.

int intValue = StrToInt(Edit1->Text); //String to Integer double
double doubleValue = StrToFloat(Edit1->Text);//String to Double

Edit1->Text = IntToStr(IntValue);         // Integer to String
Edit1->Text = FloatToStr(doubleValue);    // Double to String

4、C++ and Pascal

Question:
I am C++ programmer and not familiar with pascal. Can you
give me a few pointers that will help?

Answer:
Here are some pointers:
    - Function ( procedure ) calls don't require parenthesis.
    - When you see '.' in pascal, you probably need the '->'
      in C/C++.
Form2.Show;     (* Opascal *)
        Form2->Show();  // C++
    - Don't forget assignment operator is a colon equals
      combination ':='.
    - Create and CreateNew are Object Pascal's constructors.
    - The inherited statement is used to tell the compiler
      not to call the function named in the current class,
      but to use the one in the next class higher in the
      hierarchy. If not, there continue searching up the
      hierarchy. This is the same as the super keyword in
      Java or Smalltalk.
    - Bar = class(Foo) in Opascal says a variable of
      type class Bar inheirits compatibliliy with class Foo.

      type
        Shape = class
            . . .
        end;

        Rectangle = class(Shape)
            . . .
        end;


        Square = class(Rectangle)
            . . .
        end;

        Circle = class(Shape)
            . . .
        end;

     In example above a value of Rectangle can be assigned to
variables of type Rectangle, Shape, or TObject ( base of all
VCL classes.) At runtime a variable of type Shape can reference
an instance of Shape, Rectangle, Square, or Circle or any other
instance or a class derived from Shape.

5、Converting a String to Char*

Question:
I am trying to convert a String to char* but keep receiving
the error:
           "Cannot cast from System::AnsiString to Char*".

Below is my code.  What am I doing wrong?
String s;
        char* ch;
        s = "test";
        ch = PChar(s);

Answer:
What you need to do is use the c_str() member function of
AnsiString. Here are a couple examples:

        String s;
        const char* ch;
        s = "test";
        ch = PChar(s.c_str());

You can avoid the PChar completely if you like.

        String s;
        const char* ch;
        s = "test";
        ch = s.c_str();

6、How do I obtain a char * from an AnsiString?

Question:
I've got

AnsiString foo;

How do I pass this to a function which needs a char?
(eg., strcpy, etc).

Answer:
foo->c_str().

The c_str() method of the AnsiString class returns
a const char* which can be used to read, but not
modify, the underlying string.

7、Getting command-line arguments in BCB

Question:
How can I access the list of parameters passed at the command
line with BCB?

Answer:
You can use the following code:

for (int x=0; x <= ParamCount(); x++)
    ShowMessage(ParamStr(0));


ParamStr(0) will return the fully qualified name of the
executable file.

8、Byte alignment in C++Builder

Question:
How do I get byte alignment in a struct in C++Builder

Answer:
#pragma pack(1)
struct foo{ /* put struct definition here */ };
#pragma pack()

9、Catching exceptions in a thread

Question:
How can I catch a C++ exception in a thread.  I have created a
thread with CreateThread() and my exceptionis never caught.

Answer:
Use _beginthread().  The function CreateThread does not
initialize the RTL, which the exceptions depend on. Rumor has it
that MS may initialize some RTL stuff in there DLL's. So ,
CreateThread() may work for them, but MS say's to use
_beginthread()if you are using any "...C runtime functions..."
(mentioned at the bottom of the Help file for CreateThread()).
Thus, _beginthread IS the recommended function to use and we
have not broken or violated anything. Not a bug !!!!

10、Netscape Plug-ins SDK

Question:
Has any body been able to compile a DLL using the
Netscape Plug-in SDK and Borland's development tools?

One of the header files generates an error
'CANNOT USE EXTERN "C" WITH TEMPLATES OR OVERLOADED OPERATORS'
what is going on here?

Answer:
Certain C++ constructs cannot be wrapped in extern C
because the resulting names would not be meaningful.

The extern "C" wrapper should only be used around three functions
in npwin.cpp.

But first, ensure your .dll's name starts with np:
e.g. npplugin.dll.

Second, create an export section in you're .def file with three
Netscape functions to set up entry points:
e.g.

EXPORTS
NP_GetEntryPoints @1
NP_Initialize @2
NP_Shutdown @3

Finally, you need to wrap these three functions in the npwin.cpp
with extern "C":
e.g.

extern "C" NPError WINAPI NP_EXPORT NP_GetEntryPoints(NPPluginFuncs* pFuncs)
etc...

A good reference that discusses how to non-MS compilers is
"Programming Netscape Plug-Ins" by Zan Oliphant.
ISBN 1-57721-098-3, published by Sams-Net.

11、Exception Handling and VCL

Question:
Is there a simple way to catch exceptions in the control's
events?

Answer:
Create a method of the form to trap for exceptions.  This method
will be called on the OnException method of the application.  In
your method, check for the exception you're looking for,
ie EDatabaseError.  Check the on-line help for the OnException
event.  It has info on how to call your own method for the event.
For example:

   void __fastcall TForm1::MyException(TObject *Sender, Exception *E)
   {
      // Don't forget to do a forward declaration for this in the class
// definition.

      if (dynamic_cast<EDatabaseError*> (E))
      {
         MessageBox(0, E->Message.c_str(), "Trapped Exception", MB_OK);
      }
      else
      {
         // This is not the error you are looking for, Raise the exception.
         // ...
      }
   }

   void __fastcall TForm1::FormCreate(TObject *Sender)
   {
      Application->OnException = MyException;
   }

12、Why can't I use a member function of an object to create a thread

Question:
I'm trying to spin a thread, and I want to use a member
function as the thread procedure. But I can't get
the compiler to accept it. Why not?

Answer:
C++ does not allow this behavior.

Class methods are stored in memory in exactly (1) location.
The way that a class method accesses other members of a
class is via a pointer which is silently passed as the
first argument to the method; windows knows nothing about
this pointer, and is unable to pass it.

The compiler will not allow you to call a non-static member
function without an object because it does not know what
to store in the this pointer; if it did, you would still
not be happy with the result, because windows would NOT
pass a this pointer as the first argument.

To get around this, you can:

(a) use a static method.
(b) have a global c-style function which calls the method
of a particular object by invoking it explicitly, eg.

int foo() {
   object.method()
}

and then pass that to the thread-invocation function.

13、Errno, BC5.02, and C++Builder

Question:
I've created this static library in BC++ 5.0,
and i'm trying to use it in C++Builder, but
i'm getting linker errors regarding _errno. Why?
Shouldn't this be the same in both products?

Answer:
At first glance, it seems like it should. But
if you look at the header file, you will see
that _errno is _different_ depending on whether
or not _MT is defined. This is because the default
errno is not thread-safe, and the one provided
when _MT (which determines whether the compiler
should use the multi-threaded or non-multi-threaded
versions of the RTL) is defined is.

The defaults for this compiler define vary between
BC++ 5.02 and BC++Builder. Thus, you cannot link;
the symbol is different.

You need to rebuild your .lib in BC++ 5.02
_with _MT defined._

14、Fatal General error in .#nn files or assert failures from ilink

Question:
Problems at link time
Linker Fatal General error in .#nn files or assert failures from ILINK

Problem description:
At link time
Fatal General error in module ..\lib\vcld.#02. Sometimes it is vcld.#00 or
vcld.#01.

Using the incremental linker the error is
Fatal: Assertion failed: recLen == 0 at "IMPORT.CPP", line 486"

Answer:
There is a known problem that shows up when using typedefed instantiations
of templates in headers with precompiled headers and debug info is turned
on.  The problem will show up as general failures in .#nn with the standard
linker or asserts with the incremental linker.

The workaround is to manage your precompiled headers with #pragma
hdrstop being sure to exclude the header(s) with template typedefs
from the pch.

#include <vcl\vcl.h>
#include "mypch.h" // headers that seldom change and no templates
#pragma hdrstop
#include "mytemplates.h"


Note that the problem is really with the external-type OBJ, those .#nn files
( -He in the readme ). So you could also just turn that switch off.
Open the .MAK file and add -He- to the CFLAG1 line.

--
※ 来源:.BBS 荔园晨风站 bbs.szu.edu.cn.[FROM: 192.168.1.3]


[回到开始] [上一篇][下一篇]

荔园在线首页 友情链接:深圳大学 深大招生 荔园晨风BBS S-Term软件 网络书店