Link C++ and Excel
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: Link C++ and Excel

  1. #1
    Join Date
    Dec 2012
    Posts
    3

    Angry Link C++ and Excel

    Hi,

    I'm new to c++ forum and to c++. I'll try to be as clear as possible.

    What I'm trying to do:
    (1) Make C++ read a CSV file to set some variable.
    (2) C++ have to use those variable in some function. (Not a problem)
    (3) Export those function in a DLL file which will be call in Excel (via VBA)

    I must note that I can make both link (1) and (3) separately. But when I try to put both "link" in one code, Excel crash every time I run the function in it. The "Full" link I'm trying to make doesn't work... why?!

    About the C++ code :
    -The following code compile in Code::Blocks, but as said before, the DLL make Excel crash.
    -The exported function "TPC" is kinda useless, I just pick it up for the example
    -The File Parametre.csv is as follow:

    FirstVar,12
    SecondVar,8
    ThirdVar,20

    .h File

    #include <fstream>
    #include <iostream>
    #include <sstream>
    #include <string>
    #include <vector>
    #include <gsl/gsl_rng.h>
    #include <ctime>
    #include <cstdlib>
    #include "windows.h"

    using namespace std;

    typedef vector <double> record_t;
    typedef vector <record_t> data_t;

    istream& operator >> ( istream& ins, record_t& record )
    {
    record.clear();
    string line;
    getline( ins, line );
    stringstream ss( line );
    string field;
    while (getline( ss, field, ',' ))
    {
    stringstream fs( field );
    double f = 0.0;
    fs >> f;
    record.push_back( f );
    }

    return ins;
    }

    istream& operator >> ( istream& ins, data_t& data )
    {
    data.clear();

    record_t record;
    while (ins >> record)
    {
    data.push_back( record );
    }

    return ins;
    }

    .cpp File

    #include "header.h"
    #define EXPORT __declspec(dllexport)

    //-----------------------------------------------------------------------------
    int RD(int i)
    {
    data_t data;
    ifstream infile( "Parametre.csv" );
    infile >> data;
    if (!infile.eof())
    {
    cout << "Fooey!\n";
    }
    infile.close();
    return data[i][1];
    }

    EXPORT double __stdcall TPC(int n)
    {
    double s=0;
    for (int j=1; j<=n;j++)
    {
    s += j;
    }
    return s/RD(0);
    }

  2. #2
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: Link C++ and Excel

    Quote Originally Posted by StatisTrick View Post
    Code:
    int RD(int i)
    {
      data_t data;
      ifstream infile( "Parametre.csv" );
      infile >> data;
      if (!infile.eof())
      {
        cout << "Fooey!\n";
      }
      infile.close();
      return data[i][1];
    }
    You're trying to do console output here, of which I highly doubt it's legal in a DLL function you call from Excel. It doesn't get called the way it is now, but who knows what happens when it will do some time... Also, perhaps already the initialization of the console I/O library objects is sufficient to crash Excel. I suggest you try without that.

    On the side note, your operator definitions in header.h cause a linker error when the file is included in more than one compilation unit. Better just declare them there and put the definitions into one of the existing implementation files or create a new one.

    Please use code tags when posting code.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  3. #3
    Join Date
    Dec 2012
    Posts
    3

    Re: Link C++ and Excel

    Hi,

    thanks you for your help! I've been modifying the code into a simplier format, but it's still doesn't work... same error.

    Here's the code:

    .cpp file

    #define EXPORT __declspec(dllexport)
    #include <iostream>
    #include <sstream>
    #include <string>
    #include <fstream>
    #include <vector>
    #include "windows.h"


    using namespace std;
    vector<string> variable;
    string RD(unsigned int i)
    {
    ifstream infile("Parametre.csv");
    string line = "";
    while (getline(infile, line))
    {
    stringstream strstr(line);
    string word = "";
    while (getline(strstr,word, ','))
    {
    variable.push_back(word);
    }
    }
    return variable.at(i);
    }

    EXPORT double _stdcall TPC(int i)
    {
    //Converting the string value in RD(i) into a integer
    int Result;
    stringstream convert(RD(i));
    if ( !(convert >> Result) )
    Result = 0;

    return 2*Result;
    }

  4. #4
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: Link C++ and Excel

    Ok, the reference to cout in your code is gone now, but you're still including <iostream>. I never took a look at the internals of that header, but instantiation of global objects like cout caused by code inside the header may still result in library calls being made internally that conflict with Excel. Try removing that #include; you're not using anything from that header anymore anyway.

    Also, though RD() isn't declared EXPORT, nor there's any other sign in your demo code that you're doing that: Be aware that Excel, at least at the interface you're using here, has no idea of what an std::string is, so you can't return that across the DLL boundary. Strings are usually passed between Excel and imported DLLs in the form of BSTRs, except under some certain circumstances (that I'd need to look up now) when they're passed as LPSTR, in which case you may be allowed to modify them, but only as long as you don't change their length.

    Finally, can you explain in more detail what you mean by "crash" and "same error"?
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  5. #5
    Join Date
    Dec 2012
    Posts
    3

    Re: Link C++ and Excel

    Hi,

    I've exported the RD() function and removed #include <iostream>. Same error (will be describe at the end).

    I've found a code that seem to convert std::string to BSTRs, but seriously, I have no idea how to correctly incorporate it in my code ...

    Code to Convert std::string to BSTR (found here)
    BSTR ConvertMBSToBSTR(const std::string& str)
    {
    int wslen = ::MultiByteToWideChar(CP_ACP, 0 /* no flags */,
    str.data(), str.length(),
    NULL, 0);

    BSTR wsdata = ::SysAllocStringLen(NULL, wslen);
    ::MultiByteToWideChar(CP_ACP, 0 /* no flags */,
    str.data(), str.length(),
    wsdata, wslen);
    return wsdata;
    }
    Info on Error:
    When I try to use the function «TPC» in Excel, an small pop-up windows appear saying:
    «Microsoft Excel as stopped working. Option 1: Check Online for solution. Option 2: Close the program)»
    When I look at the problem detail:
    Problem signature:
    Problem Event Name: APPCRASH
    Application Name: EXCEL.EXE
    Application Version: 12.0.6665.5003
    Application Timestamp: 5061d2a8
    Fault Module Name: LienComplet.dll
    Fault Module Version: 0.0.0.0
    Fault Module Timestamp: 50c730ab
    Exception Code: 40000015
    Exception Offset: 0000c679
    OS Version: 6.1.7601.2.1.0.768.3
    Locale ID: 1033

    Additional information about the problem:
    LCID: 1033
    Brand: Office12Crash
    skulcid: 1033
    Additionnal Info : VBA code
    Public Declare Function TPC Lib _
    "C:\...\LienComplet.dll" (ByVal n As Long) As Double

    Public Function TP(n)
    TP = TPC(n)
    End Function

    And again, a big thanks for your time and help!

  6. #6
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: Link C++ and Excel

    Quote Originally Posted by StatisTrick View Post
    I've exported the RD() function and removed #include <iostream>. Same error (will be describe at the end).

    I've found a code that seem to convert std::string to BSTRs, but seriously, I have no idea how to correctly incorporate it in my code ...
    You probably don't need to do that at all. What I meant to say was not that you should modify RD() to return a BSTR, just that the way it was as of post #3, you can't call it directly from Excel, and as long as you don't intend to do that, it's perfectly fine. The easiest way to ensure not calling it from Excel is to simply not expose it to Excel at all, which is why I mentioned EXPORT, and not having that in your function signature was an indication to me that you don't plan to call it from Excel.

    The results I got from simply copy-pasting the exception code you got into the MSDN search field unfortunately didn't really tell me much. Maybe you are able to find something related to your scenario in there. That's all I can say by now. Perhaps I can come up with a few more ideas later...
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center