r-lib / cpp11

cpp11 helps you to interact with R objects using C++ code.
https://cpp11.r-lib.org/
Other
193 stars 46 forks source link

Unclear error when `r_string` is used as an argument #311

Open stephematician opened 1 year ago

stephematician commented 1 year ago

I know why this doesn't work; however it took a while to track down (and I didn't find help elsewhere) - so at least if I put this here it might help others.

Basic idea is what if you want to pass a 'scalar' character vector (i.e. invoke a function in R like foo("test")), it looks like the pattern I have to use is:

cpp11::cpp_source(code='
#include <string>
#include "cpp11.hpp"
[[cpp11::register]]
void foo(cpp11::strings bar) {
    if (bar.size() != 1) cpp11::stop("Expected one string");
    std::string str = bar[0];
}')
foo("hello")

No problems.

On the other hand, trying this (and hoping that cpp11 does the hard work) fails:

cpp11::cpp_source(code='
#include <string>
#include "cpp11.hpp"
[[cpp11::register]]
void foo(cpp11::r_string bar) { std::string str = bar;}')
foo("hello")
Error: 'translateCharUTF8' must be called on a CHARSXP, but got 'character'

As a suggestion, perhaps have a valid_type check on the data similar to r_vector; e.g.

// update the assignment in the constructor to check type
  r_string(SEXP data) : data_(valid_type(data)) {}
// definition of valid_type somewhere
inline SEXP r_string::valid_type(SEXP data) {
  if (data == nullptr) {
    throw std::exception( /* construct error msg */);
  }
  if (TYPEOF(data) != CHARSXP) {
    throw std::exception(/* construct error msg */);
  }
  return data;
}
Eunsolfs commented 1 year ago

hi,I met a problem in laerning R ,can you give me some help? My question link is : How to pass parameters in .R file to cpp11 function in .cpp file

thank you very much if you can lend me some time!

stephematician commented 1 year ago

hi,I met a problem in laerning R ,can you give me some help? My question link is : How to pass parameters in .R file to cpp11 function in .cpp file

thank you very much if you can lend me some time!

I don't know if you did, but I would try https://www.stackoverflow.com to post problems like this.

Eunsolfs commented 1 year ago

thank you for your help. Finally i got the solution –—— n <- sum(c(1.1,2.2,3.5)) use c(...) to pass vector of numbers

---- Replied Message ---- | From | @.> | | Date | 04/15/2023 07:27 | | To | @.> | | Cc | @.>@.> | | Subject | Re: [r-lib/cpp11] Unclear error when r_string is used as an argument (Issue #311) |

hi,I met a problem in laerning R ,can you give me some help? My question link is : How to pass parameters in .R file to cpp11 function in .cpp file

thank you very much if you can lend me some time!

I don't know if you did, but I would try https://www.stackoverflow.com to post problems like this.

— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you commented.Message ID: @.***>